x Java Java 8 JUnit JSON
  • XML
  • JDBC Spring Boot Microservices React Contact Us

    Java 8 Optional examples for null check

    An Optional class introduced in Java 8 is used to prevent NullPointerException by acting as a holder for an object that may be a null value. There are various methods provided in Optional class which can be used in checking null value. Note that if a class attribute is never going to be null, then you don't need to use Optional.

    1) Optional of(), ofNullable() & empty() example

    You can create an Optional type by using Optional.of() method. But if the value passed is null, it will throw NullPointerException. In those scenarios you can use ofNullable() instead. Below example hows how to avoid NullPointerException using Optional empty() & ofNullable().

    // Java 8 Optional ofNullable() example
    import java.util.Optional;
    
    public class TestOptional {
    
        public static void main(String[] args) {
    
            Optional<String> fruit = Optional.of("APPLE");
    
            System.out.println("Non-Empty Optional --> " + fruit);
            System.out.println("Non-Empty Optional: fruit value --> " + fruit.get());
    
            System.out.println("Empty Optional: " + Optional.empty());
    
            String fruit2 = "Mango";
            System.out.println("Optional: " + Optional.ofNullable(fruit2));
            
            fruit2 = null;
            System.out.println("Optional: " + Optional.ofNullable(fruit2));
            
            // java.lang.NullPointerException
            System.out.println("Optional: " + Optional.of(fruit2));
    
        }
    
    }	

    Console Output :

    Non-Empty Optional: fruit value --> APPLE
    Empty Optional: Optional.empty
    Optional: Optional[Mango]
    Optional: Optional.empty
    Exception in thread "main" java.lang.NullPointerException
    	at java.util.Objects.requireNonNull(Unknown Source)
    	at java.util.Optional.(Unknown Source)
    	at java.util.Optional.of(Unknown Source)
    	at TestOptional.main(TestOptional.java:21)
            

    2) Optional map() example

    map() will check if a value is present and then only will apply function on it, else will return an empty Optional

    // Java 8 Optional map() example
    import java.util.Optional;
    
    public class TestOptional {
    
        public static void main(String[] args) {
    
            Optional<String> fruit = Optional.of("APPLE");
            Optional<String> emptyFruit = Optional.empty();
    
            System.out.println("Non-Empty Optional:: " + fruit.map(String::toUpperCase));
            System.out.println("Empty Optional    :: " + emptyFruit.map(String::toUpperCase));
    
        }
    
    }	

    Console Output :

    Non-Empty Optional:: Optional[APPLE]
    Empty Optional    :: Optional.empty        

    3) Optional filter(Predicate predicate) example

    // Java 8 Optional filter() example
    import java.util.Optional;
    
    public class TestOptional {
    
        public static void main(String[] args) {
    
            Optional<String> fruit = Optional.of("APPLE");
            Optional<String> emptyFruit = Optional.empty();
    
            System.out.println(fruit.filter(f -> f.equals("MANGO"))); 
            System.out.println(fruit.filter(f -> f.equalsIgnoreCase("APPLE"))); 
            System.out.println(emptyFruit.filter(f -> f.equalsIgnoreCase("APPLE")));
    
        }
    
    }	

    Console Output :

    Optional.empty
    Optional[APPLE]
    Optional.empty
            

    4) Optional orElse(), orElseGet() & orElseThrow() examples

    // Java 8 Optional orElse(), orElseGet() & orElseThrow() examples
    import java.util.Optional;
    
    public class TestOptional {
    
        public static void main(String[] args) {
    
            Optional<String> fruit = Optional.of("APPLE");
            Optional<String> emptyFruit = Optional.empty();
    
            System.out.println(fruit.orElse("<N/A>")); 
            System.out.println(emptyFruit.orElse("<N/A>")); 
            
            System.out.println(fruit.orElseGet(() -> "<N/A>")); 
            System.out.println(emptyFruit.orElseGet(() -> "<N/A>")); 
            
            System.out.println(fruit.orElseThrow (IllegalArgumentException::new));
            System.out.println(emptyFruit.orElseThrow (IllegalArgumentException::new));
    
        }
    
    }
    	

    Console Output :

    APPLE
    <N/A>
    APPLE
    <N/A>
    APPLE
    Exception in thread "main" java.lang.IllegalArgumentException
    	at java.util.Optional.orElseThrow(Unknown Source)
    	at TestOptional.main(TestOptional.java:18)        

    5) Optional isPresent(), ifPresent(Consumer consumer) examples

    // Java 8 Optional isPresent(), ifPresent() examples
    import java.util.Optional;
    
    public class TestOptional {
    
        public static void main(String[] args) {
    
            Optional<String> fruit = Optional.of("APPLE");
            
            if (fruit.isPresent()) {
                System.out.println(fruit);
            } else {
                System.out.println("fruit is not available.");
            }
    
            Optional<String> string = Optional.of(" the quick fox ");
            string.map(String::trim).ifPresent(System.out::println);
            
            Optional<String> emptyFruit = Optional.empty();
            emptyFruit.ifPresent(f -> System.out.println("fruit is not available."));
    
        }
    
    }	

    Console Output :

    Optional[APPLE]
    the quick fox       

    References :

    Oracle Docs Optional