📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
In this tutorial, we will demonstrate the different ways to create Optional class objects in Java.
The Optional class was introduced in Java 8 to avoid null checks and NullPointerException.
The Optional class provides empty(), of(), ofNullable() methods to create it's objects.
Create Optional Class Object in Java - empty(), of(), ofNullable() Methods
There are several ways of creating Optional objects.
empty() Method
To create an empty Optional object, we simply need to use its empty() static method: Optional<Object> emptyOptional = Optional.empty();
of() Method
The of() static method returns an Optional with the specified present non-null value.
Optional<String> emailOptional = Optional.of("ramesh@gmail.com");
ofNullable() Method
The ofNullable() static method returns an Optional describing the specified value, if non-null, otherwise returns an empty Optional. Optional<String> stringOptional = Optional.ofNullable("ramesh@gmail.com");
Here is the complete example with output:
import java.util.Optional;
public class OptionalDemo {
public static void main(String[] args) {
String email = "ramesh@gmail.com";
// of, empty, ofNullable
Optional<Object> emptyOptional = Optional.empty();
System.out.println(emptyOptional);
Optional<String> emailOptional = Optional.of(email);
System.out.println(emailOptional);
Optional<String> stringOptional = Optional.ofNullable(email);
System.out.println(stringOptional);
}
}
Output:
Optional.empty
Optional[ramesh@gmail.com]
Optional[ramesh@gmail.com]
Comments
Post a Comment
Leave Comment