In Java 8, the `Optional` class was introduced as part of the Java API to deal with the issue of null values and reduce NullPointerExceptions (NPE) in code. `Optional` is a container object that may or may not contain a non-null value. It provides methods to work with values that may or may not be present, avoiding the need for explicit null checks.
Here's an example of how to use the `Optional` class in Java 8:
import java.util.Optional;
public class OptionalExample {
public static void main(String[] args) {
String name = "John Doe";
Optional optionalName = Optional.ofNullable(name);
// Check if a value is present
if (optionalName.isPresent()) {
System.out.println("Name: " + optionalName.get());
} else {
System.out.println("Name is not present.");
}
// Conditional action using ifPresent
optionalName.ifPresent(n -> System.out.println("Name: " + n));
// Default value with orElse
String defaultName = optionalName.orElse("Unknown");
System.out.println("Name: " + defaultName);
// Default value with orElseGet
String defaultValue = optionalName.orElseGet(() -> "Unknown");
System.out.println("Name: " + defaultValue);
// Custom action with orElseThrow
String nonNullName = optionalName.orElseThrow(() -> new IllegalArgumentException("Name is not present"));
System.out.println("Name: " + nonNullName);
}
}
In the example above, the `Optional.ofNullable` method is used to create an `Optional` object that may or may not contain the value `name`. The `isPresent` method is used to check if the value is present, and the `get` method is used to retrieve the value (if present).
Additionally, the `ifPresent` method allows you to perform a conditional action if the value is present. The `orElse` method provides a default value if the optional value is not present, while `orElseGet` allows you to specify a supplier function to generate a default value. The `orElseThrow` method throws an exception if the value is not present.
Using the `Optional` class can help make your code more expressive and less prone to NPEs by providing a clear way to handle potentially null values.