πŸ”Ή What is Optional?

Optional<T> is a container object that may or may not hold a non-null value.

βœ… It’s a wrapper around an object that helps you write null-safe code.


🧱 Why Use Optional?

Before Java 8:

if (obj != null) {
Β  Β  obj.doSomething();
}

With Optional:

Optional.ofNullable(obj).ifPresent(o -> o.doSomething());

πŸ“¦ How to Create Optional

Method Description
Optional.of(value) Creates an Optional with a non-null value (throws NPE if null)
Optional.ofNullable(value) Accepts null; returns empty if null
Optional.empty() Creates an empty Optional

Optional<String> name = Optional.of("Aftab");
Optional<String> empty = Optional.empty();
Optional<String> maybeName = Optional.ofNullable(null);


βœ… Common Methods in Optional

Method Description
isPresent() Returns true if value is present
ifPresent(Consumer) Runs code if value is present
get() Returns value (avoid if unsure β€” may throw)
orElse(T) Returns value or default if absent
orElseGet(Supplier) Lazy version of orElse()
orElseThrow() Throws exception if value is absent
map(Function) Transforms the value inside the Optional
flatMap(Function) Like map, but avoids nested Optionals
filter(Predicate) Filters value with condition

πŸ’‘ Examples

1. Avoiding Null Checks

Optional<String> name = Optional.ofNullable(getName());
name.ifPresent(n -> System.out.println("Hello " + n));

2. Using orElse / orElseGet

String name = Optional.ofNullable(getName()).orElse("Guest");

3. Using map to Transform

Optional<String> name = Optional.of("aftab");
String upper = name.map(String::toUpperCase).orElse("UNKNOWN");

System.out.println(upper); // Output: AFTAB


🧠 When to Use Optional

βœ… Use in:

  • Return types of methods
  • Wrapping potentially-null results (e.g., from DB or API)
  • Stream operations

🚫 Don't use in:

  • Fields in entity classes (avoid for serialization)
  • Method parameters (not a good practice)

βœ… Summary

Attribute Value
Package java.util.Optional
Purpose Null-safety, expressive API
Replaces Manual null checks
Key Benefit Avoid NullPointerException
Back to blog

Leave a comment

Please note, comments need to be approved before they are published.