Optional Class In Java Tutorials
Programming
What is Optional?
Optional is a class available in the java.util package. It was introduced in Java 8.
An Optional object can:
Contain a value
Be empty (contain no value)
The main purpose of Optional is to avoid NullPointerException (NPE).
What is NullPointerException ?
A NullPointerException occurs when we try to perform an operation on a null object.
Example
java
String s = null;
s.length(); // NullPointerExceptionHere, s is null, so calling length() causes an exception.
Traditional Null Check
Before Java 8, developers used null checks to avoid NullPointerException.
java
String s = null;
if (s != null) {
System.out.println(s.length());
}Problem
Developers may forget to check for null.
Missing a null check can cause a NullPointerException.
Too many null checks make code lengthy and difficult to maintain.
Using Optional
Without Optional
java
public String getUsernameById(Integer id) {
if (id == 100) {
return "Raju";
} else if (id == 101) {
return "Rani";
} else if (id == 102) {
return "John";
}
return null;
}Problem
The method may return null, which can lead to NullPointerException.
With Optional
java
public Optional<String> getUsername(Integer id) {
String name = null;
if (id == 100) {
name = "Raju";
} else if (id == 101) {
name = "Rani";
} else if (id == 102) {
name = "John";
}
return Optional.ofNullable(name);
}Benefit
Optional.ofNullable() safely handles both null and non-null values.
Using Optional Values
java
Optional<String> username = u.getUsername(userId);
if (username.isPresent()) {
String name = username.get();
System.out.println(name.toUpperCase() + ", Hello");
} else {
System.out.println("No Data Found");
}Explanation
isPresent()checks whether a value exists.get()retrieves the value if present.
Recommended Approach
Instead of using isPresent() and get(), modern Java projects prefer functional methods.
java
u.getUsername(userId)
.map(name -> name.toUpperCase() + ", Hello")
.ifPresent(System.out::println);Benefits
Cleaner code
Less null handling code
Easy to read and maintain
Using Default Values
If no value is present, we can provide a default value.
java
String name = u.getUsername(userId)
.orElse("Guest");
System.out.println(name);Output
If username exists:
text
RAJUIf username does not exist:
text
GuestImportant Optional Methods
of() ->Creates Optional with a non-null valueofNullable() ->Creates Optional and allows null valuesisPresent() ->Checks whether a value existsget() ->Returns the stored valueorElse() ->Returns a default value if emptyorElseGet() ->Returns value from a supplier if emptyorElseThrow() ->Throws an exception if value is not presentmap() ->Performs an operation on the valueifPresent() ->Executes code only when value exists
Key Points
Optional was introduced in Java 8.
It helps avoid NullPointerException.
An Optional object may contain a value or be empty.
Use
ofNullable()when a value can be null.Use
orElse()to provide default values.Prefer
map()andifPresent()for cleaner code.Avoid excessive use of
get()without checking the value.