📘 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.
✅ Some premium posts are free to read — no account needed. Follow me on Medium to stay updated and support my writing.
🎓 Top 10 Udemy Courses (Huge Discount): Explore My Udemy Courses — Learn through real-time, project-based development.
▶️ Subscribe to My YouTube Channel (172K+ subscribers): Java Guides on YouTube
Overview
![]() |
- Null checks are not required.
- No more NullPointerException at run-time.
- We can develop clean and neat APIs.
- No more Boilerplate code
Optional Class Simple Example
import java.util.Optional;
public class OptionalBasicExample {
public static void main(String[] args) {
Optional<String> gender = Optional.of("MALE");
String answer1 = "Yes";
String answer2 = null;
System.out.println("Non-Empty Optional:" + gender);
System.out.println("Non-Empty Optional: Gender value : " + gender.get());
System.out.println("Empty Optional: " + Optional.empty());
System.out.println("ofNullable on Non-Empty Optional: " + Optional.ofNullable(answer1));
System.out.println("ofNullable on Empty Optional: " + Optional.ofNullable(answer2));
// java.lang.NullPointerException
System.out.println("ofNullable on Non-Empty Optional: " + Optional.of(answer2));
}
}
Usage of Optional class APIs/Methods
isPresent() Optional class API
private static void isPresentOptionalAPI() {
Optional<String> opt = Optional.of("Ramesh");
System.out.println(opt.isPresent());
}
empty() Optional class API
// Returns an Optional with the specified present non-null value.
private static void createEmptyOptionalObject() {
Optional<String> empty = Optional.empty();
System.out.println(empty.isPresent());
// Optional object with the static of API:
String name = "Ramesh";
Optional.of(name);
}
ifPresent() Optional class API
private static void ifPresentOptionalAPI() {
// The ifPresent API enables us to run some code on the wrapped value if it is
// found to be non-null.
// Before Optional, we would do something like this:
String name = "Ramesh";
if (name != null) {
System.out.println(name.length());
}
Optional<String> opt = Optional.of("Ramesh");
opt.ifPresent(str -> System.out.println(str.length()));
}
orElse() Optional class API
private static void orElseOptionalAPI() {
// With orElse, the wrapped value is returned if it is present and the argument
// given to
// orElse is returned if the wrapped value is absent
String nullName = null;
// If a value is present, invoke the specified consumer with the value, otherwise
// do nothing.
String name = Optional.ofNullable(nullName).orElse("Ramesh");
System.out.println(name);
}
orElseGet() Optional class API
private static void orElseGetOptionalAPI() {
String nullName = null;
String name = Optional.ofNullable(nullName).orElseGet(() -> "Ramesh");
System.out.println(name);
}
orElseThrow() Optional class API
private static void orElseThrowOptionalAPI() {
String nullName = null;
String name = Optional.ofNullable(nullName)
.orElseThrow(IllegalArgumentException::new);
System.out.println(name);
}
get() Optional class API
private static void getOptionalAPI() {
Optional<String> opt = Optional.of("Ramesh");
String name = opt.get();
System.out.println(name);
}
Complete Example for Reference
import java.util.Optional;
public class OptionalClassExamples {
public static void main(String[] args) {
isPresentOptionalAPI();
createEmptyOptionalObject();
createEmptyOptionalObjectWithStaticAPI();
ifPresentOptionalAPI();
orElseOptionalAPI();
orElseOptionalAPI();
orElseGetOptionalAPI();
orElseThrowOptionalAPI();
getOptionalAPI();
}
// Returns an Optional with the specified present non-null value.
private static void isPresentOptionalAPI() {
Optional < String > opt = Optional.of("Ramesh");
System.out.println(opt.isPresent());
}
// Returns an Optional with the specified present non-null value.
private static void createEmptyOptionalObject() {
Optional < String > empty = Optional.empty();
System.out.println(empty.isPresent());
// Optional object with the static of API:
String name = "Ramesh";
Optional.of(name);
}
private static void createEmptyOptionalObjectWithStaticAPI() {
String name = "baeldung";
Optional.of(name);
}
// If a value is present, invoke the specified consumer with the value, otherwise do
// nothing.
private static void ifPresentOptionalAPI() {
// The ifPresent API enables us to run some code on the wrapped value if it is
// found to be non-null.
// Before Optional, we would do something like this:
String name = "Ramesh";
if (name != null) {
System.out.println(name.length());
}
Optional < String > opt = Optional.of("Ramesh");
opt.ifPresent(str -> System.out.println(str.length()));
}
// If a value is present, invoke the specified consumer with the value, otherwise do
// nothing.
private static void orElseOptionalAPI() {
// With orElse, the wrapped value is returned if it is present and the argument
// given to
// orElse is returned if the wrapped value is absent
String nullName = null;
// If a value is present, invoke the specified consumer with the value, otherwise
// do nothing.
//
String name = Optional.ofNullable(nullName).orElse("Ramesh");
System.out.println(name);
}
private static void orElseGetOptionalAPI() {
String nullName = null;
String name = Optional.ofNullable(nullName).orElseGet(() -> "Ramesh");
System.out.println(name);
}
private static void orElseThrowOptionalAPI() {
// This will throw exception
String nullName = null;
String name = Optional.ofNullable(nullName)
.orElseThrow(IllegalArgumentException::new);
System.out.println(name);
}
private static void getOptionalAPI() {
Optional < String > opt = Optional.of("Ramesh");
String name = opt.get();
System.out.println(name);
}
}
Source code on GitHub
4. Related Java 8 Top Posts
- Java 8 Lambda Expressions
- Java 8 Functional Interfaces
- Java 8 Method References
- Java 8 Stream API
- Java 8 Optional Class
- Java 8 Collectors Class
- Java 8 StringJoiner Class
- Java 8 Static and Default Methods in Interface
- Guide to Java 8 forEach Method
- Handle NullPointerException in Controller, Service, and DAO Layer using Java 8 Optional Class
- How to Use Java 8 Stream API in Java Projects
- Migrating Source Code to Java 8
Comments
Post a Comment
Leave Comment