Using Java Optional to Eliminate NullPointerException
The article explains how Java 8's Optional class can prevent NullPointerException by introducing common methods such as empty, of, isPresent, orElse, orElseGet, and orElseThrow, and demonstrates their usage with a complete code example and its output.
Background
Java developers often encounter the notorious NullPointerException. Java 8 introduced the Optional class as a step toward functional programming and a way to avoid null‑related errors.
Common Optional Methods
Optional.empty()– creates an empty Optional instance. Optional.of(T t) – creates an Optional containing t; throws an exception if t is null. isPresent() – returns true if the Optional holds a value, otherwise false. orElse(T other) – returns the contained value if present; otherwise returns the supplied default other. orElseGet(Supplier<? extends T> supplier) – returns the value if present; otherwise invokes the supplier to produce a default. orElseThrow(Supplier<? extends Throwable> supplier) – returns the value if present; otherwise throws the exception produced by the supplier.
Detailed Usage Example
import java.util.Date;
import java.util.Optional;
public class OptionalDemoTest {
public static void main(String[] arg) {
// 1. Create Optional
Optional<string> str = Optional.of("a");
// 2. Get value directly (throws if null)
System.out.println(str.get());
// 3. Check presence
System.out.println(str.isPresent());
// 4. Get value with default
System.out.println(str.orElse("b"));
// 5. Get value with supplier default
System.out.println(str.orElseGet(() -> new Date().toString()));
// 6. Get value or throw custom exception
System.out.println(str.orElseThrow(() -> new RuntimeException()));
}
}The program prints the following sequence:
a
true
a
a
aThis demonstrates how Optional can safely handle potentially null values without causing a NullPointerException.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Coder Trainee
Experienced in Java and Python, we share and learn together. For submissions or collaborations, DM us.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
