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.
Facing issues? Have Questions? Post them here! I am happy to answer!
Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.
Follow him on: X
You can also reach out to him via e-mail: rakesh@code2care.org
- Get the current timestamp in Java
- Java Stream with Multiple Filters Example
- Java SE JDBC with Prepared Statement Parameterized Select Example
- Fix: UnsupportedClassVersionError: Unsupported major.minor version 63.0
- [Fix] Java Exception with Lambda - Cannot invoke because object is null
- 7 deadly java.lang.OutOfMemoryError in Java Programming
- How to Calculate the SHA Hash Value of a File in Java
- Java JDBC Connection with Database using SSL (https) URL
- How to Add/Subtract Days to the Current Date in Java
- Create Nested Directories using Java Code
- Spring Boot: JDBCTemplate BatchUpdate Update Query Example
- What is CA FE BA BE 00 00 00 3D in Java Class Bytecode
- Save Java Object as JSON file using Jackson Library
- Adding Custom ASCII Text Banner in Spring Boot Application
- [Fix] Java: Type argument cannot be of primitive type generics
- List of New Features in Java 11 (JEPs)
- Java: How to Add two Maps with example
- Java JDBC Transition Management using PreparedStatement Examples
- Understanding and Handling NullPointerException in Java: Tips and Tricks for Effective Debugging
- Steps of working with Stored Procedures using JDBCTemplate Spring Boot
- Java 8 java.util.Function and BiFunction Examples
- The Motivation Behind Generics in Java Programming
- Get Current Local Date and Time using Java 8 DateTime API
- Java: Convert Char to ASCII
- Deep Dive: Why avoid java.util.Date and Calendar Classes
- [Fix] zsh: command not found: awscli [Mac Terminal] - AWS
- Download Google Chrome setup exe file using PowerShell - Powershell
- New-SPLogFile PowerShell - create new SharePoint log file - SharePoint
- Two Ways to Extract rar (*.rar) files on Mac - MacOS
- Check version of pip package installer for Python - Python
- SharePoint - Use Today's Date Time in list view filter and calculated column - SharePoint
- Notepad++ Save Failed - Please check if this file is opened in another program. - NotepadPlusPlus
- How to fix Microsoft Windows 10 update error 80070020 - Microsoft