Nearby lessons

95 of 125

Java - Optional Class

📌 What You Will Learn
  • Lambda expressions — the big change
  • Functional interfaces
  • Default and static methods in interfaces
  • The four workhorses: Predicate, Function, Consumer, Supplier
  • Method references (::)
  • The Stream API for processing collections
  • Optional — safe null handling
  • The new Date and Time API

Optional Class is a core concept of the Java language. This lesson explains Optional — Safe Null Handling with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.

Optional — Safe Null Handling

NullPointerException is the most common crash in Java. Optional is a box that either has a value or is empty — forcing us to check safely instead of blindly using null.

In simple words: Optional is a box that either holds a value or is empty. Instead of checking if (x != null) everywhere, you ask the box with isPresent() and give a safe default with orElse().
Example01
JCode Cell
1import java.util.Optional;
2 
3class OptionalDemo {
4 public static void main(String[] args) {
5 Optional<String> name = getName(true);
6 
7 if (name.isPresent()) {
8 System.out.println("Hello " + name.get());
9 }
10 
11 // or: give a default when empty
12 String result = name.orElse("Guest");
13 System.out.println("Result: " + result);
14 }
15 
16 static Optional<String> getName(boolean found) {
17 if (found) return Optional.of("Rahul");
18 return Optional.empty();
19 }
20}
Output
Hello Rahul Result: Rahul
📝 Key Takeaways
  • Lambda = a function without a name; (params) -> logic.
  • Functional interface = one abstract method, so a lambda can implement it.
  • Interfaces now have default and static methods with bodies.
  • Predicate (test), Function (apply), Consumer (accept), Supplier (get) are the four core functional interfaces.
  • Method references (::) are shorthand for lambdas.
  • Streams process collections with filter/map/sorted/collect pipelines.
  • Optional prevents NullPointerException with orElse/isPresent.
  • java.time (LocalDate, LocalDateTime) replaces the old Date/Calendar cleanly.

🧠 Test Your Knowledge

1 Questions
Progress: 0 / 1