Help Save Code2care! 😢

I've lost 99% of my revenue to AdBlockers & AI. Your support could be the lifeline that keeps this passion project alive!

Buy Code2care a Coffee QR Code

Scan to Buy Me A Coffee and help me continue coding for you!

When to use of() and ofNullable() methods of Optional in Java?


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!

Author Info:

Rakesh (He/Him) has a Masters Degree in Computer Science with over 15+ 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

Copyright Code2care © 2024 | Privacy Policy | About Us | Contact Us | Search