To check if a Java Optional has a value, you can use the isPresent() or isEmpty() methods:
- Using
isPresent()
This method returnstrueif theOptionalcontains a value, andfalseif it is empty.Optional<String> optional = Optional.of("Hello"); if (optional.isPresent()) { System.out.println("Value is present: " + optional.get()); } else { System.out.println("Value is not present."); } - Using
isEmpty()
Starting from Java 11, you can use theisEmpty()method, which is the opposite ofisPresent(). It returnstrueif theOptionalis empty, andfalseotherwise.Optional<String> optional = Optional.empty(); if (optional.isEmpty()) { System.out.println("Value is not present."); } else { System.out.println("Value is present: " + optional.get()); } - Using
ifPresent()
If you only need to execute code when the value is present, you can use theifPresent()method, which takes a lambda expression or a method reference to process the value.Optional<String> optional = Optional.of("Hello"); optional.ifPresent(value -> System.out.println("Value: " + value));
Best Practices
- Avoid calling
optional.get()without checking if the value is present; otherwise, it will throw aNoSuchElementExceptionif theOptionalis empty. - Use
ifPresent()wherever possible to handle the value directly, avoiding explicit checks withisPresent().
