Tuesday, 31 March 2020

Java8: Optional.of vs Optional. ofNullable

Optional.of method takes an element and return Optional with the specified element. If the given element is null, then Optional.of method throws NullPointerException.

Optional.ofNullable method takes an element and return Optional with the specified element. If the given element is null, then Optional.ofNullable method return empty optional.

If the element is not null, then both Optional.of and Optional.ofNullable behavior is same. But in case of null, Optional.of throws NullPointerException, whereas Optional.ofNullable return empty Optional.

App.java
package com.sample.app;

import java.util.NoSuchElementException;
import java.util.Optional;

public class App {

    public static void main(String args[]) {
        String str = "Hello World";

        Optional<String> optionalOf = Optional.of(str);
        Optional<String> optionalNullable = Optional.ofNullable(str);

        System.out.println("For non null value");
        System.out.println("\toptionalOf1 : " + optionalOf.get());
        System.out.println("\toptionalNullable : " + optionalNullable.get());

        str = null;

        System.out.println("\nFor null value");
        try {
            optionalOf = Optional.of(str);
        } catch (NullPointerException e) {
            System.out.println("\tNullPointerException thrown for 'Optional.of' method");
        }

        optionalNullable = Optional.ofNullable(str);

        try {
            System.out.println("optionalNullable : " + optionalNullable.get());
        } catch (NoSuchElementException e) {
            System.out.println("\tNoSuchElementException thrown for 'optionalNullable.get()' method");
        }

    }

}

Output

For non null value
    optionalOf1 : Hello World
    optionalNullable : Hello World

For null value
    NullPointerException thrown for 'Optional.of' method
    NoSuchElementException thrown for 'optionalNullable.get()' method



Previous                                                    Next                                                    Home

No comments:

Post a Comment