How to do it...

  1. Create an Optional object using any of the methods that have been demonstrated, as follows:
Optional<Integer> prize1 = Optional.empty();System.out.println(prize1.isPresent()); //prints: falseSystem.out.println(prize1);   //prints: Optional.emptyOptional<Integer> prize2 = Optional.of(1000000);System.out.println(prize2.isPresent()); //prints: trueSystem.out.println(prize2);  //prints: Optional[1000000]//Optional<Integer> prize = Optional.of(null);                                   //NullPointerExceptionOptional<Integer> prize3 = Optional.ofNullable(null);System.out.println(prize3.isPresent());  //prints: falseSystem.out.println(prize3);     //prints: Optional.empty

Notice that a null value can be wrapped inside an Optional object by using the ofNullable() method. ...

Get Java 11 Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.