Optional class is a public final class and used to deal with NullPointerException in Java application. You must import java.util package to use this class. It provides methods which are used to check the presence of value for particular variable.
import java.util.Optional;
public class OptionalExample {
public static void main(String[] args) {
Optional<String> optionalName = Optional.of("John");
// Check if a value is present
if (optionalName.isPresent()) {
System.out.println("Name is present: " + optionalName.get());
}
// Providing a default value if the optional is empty
String name = optionalName.orElse("Default Name");
System.out.println("Name or default: " + name);
// Handling the case when a value is absent
Optional<String> emptyOptional = Optional.empty();
String defaultName = emptyOptional.orElse("Default Name");
System.out.println("Default name from empty optional: " + defaultName);
// Throwing an exception if a value is absent
try {
String nameOrThrow = emptyOptional.orElseThrow(IllegalStateException::new);
System.out.println("Name or throw: " + nameOrThrow);
} catch (IllegalStateException e) {
System.out.println("Caught IllegalStateException: " + e.getMessage());
}
}
}
Комментариев нет:
Отправить комментарий