Skip to content
C

Optional

Optional is a container object that may or may not hold a non-null value. It's used to represent the possibility that a value might be missing, without directly using null.


1. What is Optional?

Optional is a container object that may or may not hold a non-null value. It's used to represent the possibility that a value might be missing, without directly using null.

2. Why is it used?

Directly working with null values often causes unexpected NullPointerException errors. Optional forces you to explicitly check whether a value is present before using it, reducing this common source of bugs.

3. Real-Life Example

Think of a sealed box labeled "may or may not contain an item," which you must deliberately open and check before assuming there's something inside. Optional represents this same "might be empty" possibility clearly, instead of silently allowing a hidden, unexpected null.

4. Syntax

java
Optional<DataType> optionalValue = Optional.of(value); Optional<DataType> emptyValue = Optional.empty();

5. Example Program

java
import java.util.Optional; public class OptionalDemo { public static void main(String[] args) { Optional<String> name = Optional.ofNullable(null); System.out.println(name.isPresent() ? name.get() : "No name provided"); } }

Output:

No name provided

6. Key Points to Remember

  • Optional.of() throws an error if given a null value directly; Optional.ofNullable() safely allows null.
  • isPresent() checks if a value exists; get() retrieves it (only safe after checking isPresent()).
  • Optional is mainly intended for method return types, to clearly signal that a result might be absent.