A NullPointerException (NPE) is Java’s most common runtime exception. It occurs when you try to use a reference that points to null as if it pointed to an actual object.
Example:
String s = null;
System.out.println(s.length()); // ❌ NullPointerExceptionBelow are the typical situations:
obj.method(); // obj is null → NPEemployee.name = "Bob"; // employee is nullint[] arr = null;
int len = arr.length; // NPEInteger x = null;
int y = x; // ❌ NPE (unboxing)person.getAddress().getCity(); // if getAddress() is null → NPEif (s != null) {
System.out.println(s.length());
}Objects.requireNonNull(obj, "Object cannot be null");Initialize fields properly to avoid null defaults.
Optional<T> is a container object introduced in Java 8 that may contain a non-null value, or may be empty.
Purpose:
- Avoid returning null
- Avoid NullPointerExceptions
- Write cleaner, expressive, functional code
Use when value is guaranteed non-null.
Optional<String> opt = Optional.of("Hello");If value is null, this throws NPE.
Use when value may or may not be null.
Optional<String> opt = Optional.ofNullable(name);Represents empty Optional.
Optional<String> opt = Optional.empty();if (opt.isPresent()) {
System.out.println(opt.get());
}if (opt.isEmpty()) {
System.out.println("No value");
}String value = opt.get(); // Throws NoSuchElementException if emptyUse safer alternatives below.
Provides a default value.
String value = opt.orElse("Default");Uses a supplier function (lazy version of orElse).
String value = opt.orElseGet(() -> "Generated default");Throws a custom exception.
String value =
opt.orElseThrow(() -> new IllegalArgumentException("Value missing"));Applies a function if value is present.
Optional<String> upper =
opt.map(s -> s.toUpperCase());Used when the function returns another Optional.
Optional<String> city =
person.getAddress() // Optional<Address>
.flatMap(Address::getCity); // Optional<String>Optional<String> result =
Optional.of("Java")
.filter(s -> s.startsWith("J"));If filter fails → returns empty Optional.
String city = person.getAddress().getCity().getName();This throws NPE if any step is null.
String city =
Optional.ofNullable(person)
.map(Person::getAddress)
.map(Address::getCity)
.map(City::getName)
.orElse("Unknown");This eliminates NPE completely.
Optional should NOT be used:
- As a field in a class (adds overhead)
- For method parameters
- In collections
- In performance-critical areas
Correct use-case: method return types.
Accessing a method/field of a null reference.
It wraps potentially null values and forces safe handling.
| Method | Behavior |
|---|---|
of(value) |
Throws NPE if value is null |
ofNullable(value) |
Accepts null and wraps as empty Optional |
No. It should mainly be used as a return type.
orElse()→ evaluates default value eagerlyorElseGet()→ evaluates default value lazily
-
NullPointerException occurs when dereferencing a null reference.
-
Optional helps avoid NPE through safe, expressive APIs.
-
Use Optional for return types that may contain null.
-
Do not rely on Optional for class fields or method parameters.
-
Use
map(),flatMap(),filter(),orElse()to handle values elegantly.