String name = null; OptionaloptionalName = Optional.ofNullable(name); if(optionalName.isPresent()){ System.out.println("Name is " + optionalName.get()); } else{ System.out.println("Name is not present"); }
Integer age = 20; OptionalIn this example, the age variable is not null so the Optional object created using ofNullable method will contain the value 20. The orElse method is used to provide a default value if the Optional object is empty. In this case, since the Optional object contains a value, the age value 20 will be printed. The java.util Optional class is part of the Java Standard Library.optionalAge = Optional.ofNullable(age); System.out.println("Age is " + optionalAge.orElse(18));