Java FAQ: Top Questions
34. What is the Optional class in Java?
The
Optional
class, introduced in Java 8 in
java.util
, is a container for a value that may or may not be present, reducing
NullPointerException
risks.
-
Creation:
Optional.of(value),Optional.ofNullable(value),Optional.empty(). -
Methods:
orElse,orElseGet,map,filter,ifPresent. - Best Practice: Avoids explicit null checks, improves readability.
- Use Case: Handling potentially absent values in APIs or streams.
