If you want to create an Optional type object in Java, you can make use of either of () and ofNullable() methods.
Let's try and understand when to use which.
Optional.of(T t)
One should make use of the static of(T t) method when quite sure that the value of the object is non-null.
It is important to note that if the provided object is null, you will get a NullPointerException when trying to perform operations on a null value.
Example:import java.util.Optional;
public class ExampleOptionalOf {
public static void main(String[] args) {
String strObject1 = "Coe2care";
Optional<String> optionalValue1 = Optional.of(strObject1);
optionalValue1.ifPresent(System.out::println);
String strObject2 = null;
Optional<String> optionalValue2 = Optional.of(strObject2);
optionalValue2.ifPresent(System.out::println);
}
}
Output:
Coe2care
Exception in thread "main" java.lang.NullPointerException
at java.base/java.util.Objects.requireNonNull(Objects.java:233)
at java.base/java.util.Optional.of(Optional.java:113)
at ExampleOptionalOf.main(ExampleOptionalOf.java:12)
Optional.ofNullable(T t)
The ofNullable(T t) static method is more lenient and can handle null values.
Example:import java.util.Optional;
public class ExampleOptionalOfNullable {
public static void main(String[] args) {
String strObject1 = "Coe2care";
Optional<String> optionalValue1 = Optional.ofNullable(strObject1);
optionalValue1.ifPresent(System.out::println);
String strObject2 = null;
Optional<String> optionalValue2 = Optional.ofNullable(strObject2);
optionalValue2.ifPresentOrElse(
System.out::println,
() -> System.out.println("Value is empty!"));
}
}
Conculstion
- Use Optional.of(T t) when certain the value is non-null, note - risking a NullPointerException if null.
- Use Optional.ofNullable(T t) for flexibility, handling both non-null and null values without causing exceptions.
You can download this article in various formats for your convenience. Choose from the options below:
Facing issues? Have Questions? Post them here! I am happy to answer!
- Java Jackson ObjectMapper Class with Examples
- How to add a Delay of a Few Seconds in Java Program
- Java SE JDBC Select Statement Example
- How to Word-Warp Console logs in IntelliJ
- Convert Java Array to ArrayList Code Example
- [Java] Error: Unmappable character for encoding UTF-8. Save could not be completed.
- Maven BUILD FAILURE: Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin
- How to extract Java Jar/War/Ear files in Linux
- Java: Convert String to Binary
- Java Generics: Type parameter cannot be instantiated directly
- How to Create and Run a Command Line Application using Spring Boot
- How to Convert a Java Object into an Optional with Example
- [Hibernate] The method buildSessionFactory() from the type Configuration is deprecated
- How to Set JAVA_HOME PATH to Mac .zshrc profile file
- Formatting Double in Java [Examples]
- Java 8: Stream map with Code Examples
- Fix: SyntaxError: ( was never closed [Python]
- Java Split String by Spaces
- [fix] Java JDBC SQLSyntaxErrorException: Unknown database
- Fix: SpringFramework BeanDefinitionValidationException: Could not find an init method named
- Java Date Time API: LocalDateTime get(TemporalField field) examples
- How to create Date in yyyy-MM-dd format in Java
- Java: Create Temporary Directory and File and Delete when application terminates
- Fix RabbitMQ: AuthenticationFailureException: ACCESS_REFUSED
- Run Java Code Every Second
- How to Change Mouse Wheel Scroll Direction on Mac - MacOS
- Superscript and Subscript text in HTML - Html
- 🎃 Trending, Popular Halloween hashtags for year 2020 🎃 [Facebook, Twitter, Instagram, Snapchat] - Hashtags
- say command macOS terminal examples - MacOS
- Select Line Number TextEdit on Mac - MacOS
- Open Current Directory in Finder using Mac Terminal - MacOS
- New Features in Java 5 (Sept 2004) - Java
- How to Add Hover Effect on a HTML Button using CSS Code - CSS