The Optional class in Java 8
The Optional class was introduced in Java 8, to provide a more robust way of dealing with null values.
- Optional is a wrapper class that can store an object of type <T>.
- According to Oracle, an Optional is a container that can store an object of type <T> or null.
- Optional is a final class present in the java. util package.
- In Java 8, a new class called Optional was added.
- To avoid null pointer exceptions, Optional is used.
Here’s an explanation of Optional with an example:
Step: 1 Create a POJO class named Student.java
package com.shorts.java8.optionalclass;
public class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
// cregetter and setter
Step: 2 Create a Service class named StudentService.java
package com.shorts.java8.optionalclass;
import java.util.*;
public class StudentService {
public Map<Integer, Student> studentMap;
public StudentService() {
studentMap = new HashMap<>();
// Assume studentMap is initialized with some data
studentMap.put(1, new Student("Muna", 1));
}
public Optional<Student> getStudentById(int id) {
Student newStudent = studentMap.get(id);
Optional<Student> existStudent = Optional.ofNullable(newStudent);
return existStudent;
}
}Step: 3 Create a Main class named OptionalDemo.java
package com.shorts.java8.optionalclass;
import java.util.Optional;
public class OptionalDemo {
public static void main(String[] args) {
StudentService studentService = new StudentService();
Optional<Student> student = studentService.getStudentById(1);
if (student.isPresent()) {
System.out.println("The name of student -> " + student.get().getName());
System.out.println("The age of student -> " + student.get().getAge());
} else {
System.out.println("No student found");
}
}
}What is the difference between isPresent() and isEmpty() ?
In Java’s Optional class, isPresent() and isEmpty() are methods used to check the presence of a value within an Optional object.
isPresent()
- It is typically used to perform actions on the value only if it is present, avoiding NullPointerException errors.
- This method returns true if the Optional object contains a non-null value, and false otherwise.
Example:
Optional<String> optional = Optional.of("value");
if (optional.isPresent()) {
System.out.println("Value is present: " + optional.get());
}isEmpty()
- This method returns true if the Optional object is empty (i.e., it does not contain a value or contains a null value), and false if it contains a non-null value.
- It is mainly used for cases where you want to handle both empty and non-empty Optional instances differently.
Example:
Optional<String> optional = Optional.empty();
if (optional.isEmpty()) {
System.out.println("Optional is empty");
}The differences between Optional.ofNullable(), Optional.of(), and Optional.empty()
in Java’s Optional class, these methods are related to how they handle the presence or absence of values.
Optional.ofNullable()
- This method creates an Optional object that may contain a non-null value. If the provided value is not null, it will be wrapped in an Optional object.
- If the provided value is null, it will return an empty Optional.
Example:
Optional<String> optionalWithValue = Optional.ofNullable("val");
// Contains "val"
Optional<String> optionalWithNull = Optional.ofNullable(null);
// Empty OptionalOptional.of()
- This method creates an Optional object that contains the specified non-null value. If the value provided to of() is null, it will throw a NullPointerException.
Example:
Optional<String> optionalWithValue = Optional.of("value");
// Contains "value"Optional.empty()
- This method creates an empty Optional object, meaning it does not contain any value (equivalent to null).
Example:
Optional<String> optionalEmpty = Optional.empty(); // Empty OptionalIn summary
- Optional.ofNullable(“value”) can contain a non-null value or be empty if the provided value is null.
- Optional.of(“value”) creates an Optional object with a non-null value.
- Optional.empty() creates an empty Optional object without any value.
The difference between ifPresent() and ifPresentOrElse() methods in Java’s Optional.
These methods execute different actions based on whether the Optional an object contains a value or is empty.
ifPresent(Consumer<? super T> action)
- This method is used to perform an action if the
Optionalobject contains a non-null value. - It takes a
Consumerfunctional interface as an argument, which represents the action to be performed on the value if it is present. - In this bellow example, the lambda expression val -> System.out.println(“Value is present: “ + val) is executed only if the Optional contains a value (“value” in this case).
Example
Optional<String> optional = Optional.of("value");
optional.ifPresent(val -> System.out.println("Value is present: " + val));ifPresentOrElse(Consumer<? super T> action, Runnable emptyAction)
- This method was introduced in Java 9.
- It allows you to specify different actions for when the Optional object contains a value and when it is empty.
- It takes two arguments: a Consumer functional interface for the action to be performed if the Optional contains a value, and a Runnable interface for the action to be performed if the Optional is empty.
Optional<String> optionalWithValue = Optional.of("value");
Optional<String> optionalEmpty = Optional.empty();
optionalWithValue.ifPresentOrElse(
val -> System.out.println("Value is present: " + val),
() -> System.out.println("Optional is empty")
);
optionalEmpty.ifPresentOrElse(
val -> System.out.println("Value is present: " + val),
() -> System.out.println("Optional is empty")
);In this example, the first ifPresentOrElse call will execute the first action because optionalWithValue contains a value.
Get Java Fusion’s stories in your inbox
Join Medium for free to get updates from this writer.
The second ifPresentOrElse call will execute the second action because optionalEmpty is empty.
In summary
ifPresent() is used to execute an action if the Optional contains a value, while ifPresentOrElse() allows you to specify separate actions for when the Optional contains a value and when it is empty.
Thank you !!!










