Junior — Middle
Do you have experience using the Optional class in your projects?
sobes.tech AI
Answer from AI
Yes, the Optional class in Java is used to explicitly represent a value that may be present or absent (null). It helps to avoid NullPointerException and makes the code more readable.
Example of usage:
import java.util.Optional;
public class Example {
public static Optional<String> findNameById(int id) {
if (id == 1) {
return Optional.of("Alice");
} else {
return Optional.empty();
}
}
public static void main(String[] args) {
Optional<String> name = findNameById(2);
// Safely handle the absence of a value
name.ifPresentOrElse(
n -> System.out.println("Name: " + n),
() -> System.out.println("Name not found")
);
}
}
In projects, I used Optional for methods that may return a value or not, which improves handling of missing data and reduces the likelihood of errors.