O'Reilly logo

Java 11 Cookbook by Mohamed Sanaulla, Nick Samoylov

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required