capypad
0 day streak
java / intermediate
Snippet

Safely Handling Null with Optional

The Optional class is a container object used to represent the presence or absence of a value, helping to avoid NullPointerExceptions.

snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
import java.util.Optional;
 
public class OptionalDemo {
public static void main(String[] args) {
Optional<String> name = Optional.ofNullable(getName());
String result = name.map(String::toUpperCase)
.orElse("DEFAULT");
System.out.println(result);
}
 
static String getName() { return null; }
}
Breakdown
1
Optional.ofNullable(getName())
Creates an Optional that may hold a null value safely.
2
.orElse("DEFAULT")
Provides a fallback value if the Optional is empty.