import java.util.Optional; public class OptionalExample { public static void main(String[] args) { Optionaloptional = Optional.of("Hello World"); optional.ifPresent(System.out::println); } }
Hello World
import java.util.Optional; public class OptionalExample { public static void main(String[] args) { Optionaloptional = Optional.ofNullable(null); optional.ifPresentOrElse(System.out::println, () -> System.out.println("Value is null")); } }
Value is nullThe java.util Optional class is part of the Java Standard Library package, which is automatically imported into Java programs.