tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Java 8 Features > Stream API > Optional Class

Optional Class

Author: Venkata Sudhakar

Java 8 introduced the Optional class to handle null values gracefully and avoid NullPointerException. It acts as a container object that may or may not contain a non-null value.

Key Optional Methods:

1. Optional.of(value) - Creates an Optional with a non-null value.

2. Optional.ofNullable(value) - Creates an Optional that may hold null.

3. Optional.empty() - Creates an empty Optional.

4. isPresent() - Returns true if value is present.

5. orElse(default) - Returns value or default if empty.

The below example shows how to use Optional to avoid NullPointerException.


It gives the following output,

Name present: true
Name value: Alice
Empty present: false
orElse: Default Name
orElseGet: Generated Default
Name length: 5
Long name: Alice
Hello, Alice!
Caught: No value present!

Best Practices for Optional:

1. Never use Optional.get() without isPresent() - use orElse() or orElseThrow() instead.

2. Do not use Optional as method parameter - use it as return type only.

3. Do not use Optional for class fields - it is not Serializable.

4. Prefer ifPresent() or map() over explicit null checks for cleaner code.


 
  


  
bl  br