Loading content...
Loading content...
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).
A NullPointerException occurs when we try to perform an operation on a null object.
java
String s = null;
s.length(); // NullPointerExceptionHere, s is null, so calling length() causes an exception.
Before Java 8, developers used null checks to avoid NullPointerException.
java
String s = null;
if (s != null) {
System.out.println(s.length());
}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.
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;
}The method may return null, which can lead to NullPointerException.
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);
}Optional.ofNullable() safely handles both null and non-null 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");
}isPresent() checks whether a value exists.
get() retrieves the value if present.
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);Cleaner code
Less null handling code
Easy to read and maintain
If no value is present, we can provide a default value.
java
String name = u.getUsername(userId)
.orElse("Guest");
System.out.println(name);If username exists:
text
RAJUIf username does not exist:
text
Guestof() -> Creates Optional with a non-null value
ofNullable() -> Creates Optional and allows null values
isPresent() -> Checks whether a value exists
get() -> Returns the stored value
orElse() -> Returns a default value if empty
orElseGet() -> Returns value from a supplier if empty
orElseThrow() -> Throws an exception if value is not present
map() -> Performs an operation on the value
ifPresent() -> Executes code only when value exists
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() and ifPresent() for cleaner code.
Avoid excessive use of get() without checking the value.