Optional is a generic class defined in the java.util It facilitates the handling of potentially absent values in a more concise and expressive manner.package, that got introduced in Java 8. It provides a container-like structure to wrap objects, indicating the possibility of a value being present or absent.
Its primary purpose is to provide a safer alternative to handling null values, thereby reducing the risk of NullPointerException. By explicitly acknowledging the possibility of an absent value, Optional encourages developers to write more robust and error-resistant code.j
public String getStudentName() {
// can be null or non-null value
Student student = fetchStudent();
if(student != null){
return student.getName();
}else {
return null;
}
}
public Optional getStudentName() {
// can be null or non-null value
Optional student = Optional.ofNullable(fetchStudent());
if(student.isPresent()){
return Optional.of(student.getName());
}
return Optional.empty();
}
1. Optional.of(T value):
String name = "John Doe";
Optional<String> optionalName = Optional.of(name);
System.out.println("Optional Name: " + optionalName);
Output: Optional Name: Optional[John Doe]
2. Optional.ofNullable(T value):
String city = null;
Optional<String> optionalCity = Optional.ofNullable(city);
System.out.println("Optional City: " + optionalCity);
Output: Optional City: Optional.empty
3. Optional.empty():
Optional<String> optionalEmail = Optional.empty();
System.out.println("Empty Optional Email: " + optionalEmail);
Output: Empty Optional Email: Optional.empty
Using the Optional instance, the following methods can be utilized to manipulate and retrieve values.
1. boolean isPresent():
Optional<String> optionalName = Optional.of("John Doe");
if (optionalName.isPresent()) {
System.out.println("Name: " + optionalName.get());
} else {
System.out.println("No name found.");
}
Output: Name: John Doe
2. T get():
Optional<String> optionalName = Optional.of("John Doe");
String name = optionalName.get();
System.out.println("Name: " + name);
Output: Name: John Doe
3. T orElse(T defaultValue):
Optional<String> optionalCity = Optional.empty();
String city = optionalCity.orElse("Unknown City");
System.out.println("City: " + city);
Output: City: Unknown City
4. T orElseGet(Supplier<? extends T> supplier):
Optional<String> optionalEmail = Optional.empty();
String email = optionalEmail.orElseGet(() -> "abc@def.com");
System.out.println("Email: " + email);
Output: Email: abc@def.com
5. T orElseThrow(Supplier<? extends X> exceptionSupplier):
Optional<String> optionalName = Optional.empty();
String name = optionalName
.orElseThrow(() -> new IllegalArgumentException("Name is absent"));
Output: Exception in thread "main" java.lang.IllegalArgumentException: Name is absent
6. void ifPresent(Consumer<? super T> consumer):
Optional<String> optionalPhone = Optional.of("123456789");
optionalPhone.ifPresent(phone -> System.out.println("Phone: " + phone));
Output: 123456789