How do you use Optional with a simple code example?

Optional is a container that may or may not contain a non-null value. It helps to avoid null pointer exceptions and makes your code more readable. Here’s a simple example of how to use Optional in Java:

import java.util.Optional; public class OptionalExample { public static void main(String[] args) { Optional optionalValue = Optional.ofNullable(getValue()); // Using ifPresent() method optionalValue.ifPresent(value -> System.out.println("Value is present: " + value)); // Using orElse() method String defaultValue = optionalValue.orElse("Default Value"); System.out.println("Value is: " + defaultValue); } public static String getValue() { // Return null to simulate absence of value return null; } }

Optional Java null pointer exception Java 8 best practices