NullPointerException in Java
Problem
A NullPointerException is thrown when code tries to use a reference that doesn't point to any object yet — calling a method, reading a field, or indexing through a null value.
Call a method on a String reference that hasn't been assigned an object, and handle the resulting exception.
Java Program
public class NullPointerExceptionDemo {
public static void main(String[] args) {
String text = null;
try {
int length = text.length(); // text has no object to call length() on
System.out.println("Length: " + length);
} catch (NullPointerException e) {
System.out.println("Error: Cannot call length() on a null reference");
}
}
}Output
Core Logic
Wrapping the risky method call in try-catch lets the null reference be caught after the fact, instead of crashing the program.
- 1
String text = null;declares a reference that doesn't point to any actual String object. - 2
text.length()tries to invoke a method through that null reference, which the JVM cannot do. - 3This throws a
NullPointerExceptionat the moment of the call, beforelength()ever runs. - 4The
catch (NullPointerException e)block catches it and prints a message instead of letting the program crash.
text holding null, calling text.length() throws immediately, caught and printed as "Error: Cannot call length() on a null reference".Key Point: The exception is thrown at the point of use — calling .length() — not at the point where text was assigned null; declaring a null reference is perfectly legal, only using it isn't.
Key Concepts
Approach 2: Java 8
import java.util.Optional;
public class NullPointerExceptionOptional {
public static void main(String[] args) {
String text = null;
// Optional.ofNullable(null) is empty, so map() is skipped and orElse() supplies the fallback
String message = Optional.ofNullable(text)
.map(String::length)
.map(len -> "Length: " + len)
.orElse("Error: Cannot call length() on a null reference");
System.out.println(message);
}
}
Output
Core Logic
Optional.ofNullable() wraps the possibly-null reference itself, so length() is only ever called on a value known to be present — the null case is handled by orElse() instead of a catch block.
- 1
Optional.ofNullable(text)wrapstext, producing an emptyOptionalsincetextisnull. - 2
.map(String::length)would calllength()on the wrapped value, but only runs when theOptionalis actually present — it's skipped entirely here. - 3
.map(len -> "Length: " + len)formats the result iftexthad held a real String. - 4
.orElse("Error: Cannot call length() on a null reference")supplies the fallback message for the empty case, withoutlength()ever being invoked on a null reference.
text holding null, Optional.ofNullable(text) is empty, so both map() calls are skipped and orElse(...) supplies the error message.Key Point: No NullPointerException is ever thrown in this version — Optional makes the null case part of the value's type, so it's handled by orElse() as regular data flow instead of by catching an exception after the fact.