import java.util.Optional; public class OptionalExample { public static void main(String[] args) { // Creating an Optional with a non-null value Optional<String> optionalWithValue = Optional.of("Hello, Optional!"); System.out.println("Optional with value: " + optionalWithValue); // Creating an empty Optional Optional<String> emptyOptional = Optional.empty(); System.out.println("Empty Optional: " + emptyOptional); // Using isPresent() to check if the Optional has a value if (optionalWithValue.isPresent()) { System.out.println("Value is present: " + optionalWithValue.get()); } else { System.out.println("No value present."); } // Using ifPresent() to perform an action if a value is present optionalWithValue.ifPresent(value -> System.out.println("Optional contains: " + value)); // Using orElse() to provide a default value if the Optional is empty String defaultValue = emptyOptional.orElse("Default Value"); System.out.println("Value from empty Optional: " + defaultValue); // Using orElseGet() with a Supplier to provide a default value String generatedValue = emptyOptional.orElseGet(() -> "Generated Default Value"); System.out.println("Generated value from empty Optional: " + generatedValue); // Using map() to transform the value if present Optional<String> upperCaseOptional = optionalWithValue.map(String::toUpperCase); System.out.println("Transformed value: " + upperCaseOptional.orElse("No value to transform")); // Chaining methods: map and orElse String finalResult = optionalWithValue .map(String::toUpperCase) .orElse("No value to transform"); System.out.println("Chained transformation result: " + finalResult); } }