Module: | Multithreading, Collections & I/O Streams
Q67: Consider the following statements regarding the java.util.Optional class:
1. The Optional class acts as a secure container object specifically architected to prevent catastrophic NullPointerException crashes by explicitly representing the potential absence of a value.
2. The orElseGet() method allows the developer to pass a Supplier functional interface, ensuring the fallback logic is lazily evaluated only if the Optional is genuinely empty.
3. Modern enterprise standards strongly mandate utilizing Optional objects as method parameters and serializable class fields to maximize memory efficiency across network boundaries.
Which of the above statements is/are correct?
2. The orElseGet() method allows the developer to pass a Supplier functional interface, ensuring the fallback logic is lazily evaluated only if the Optional is genuinely empty.
3. Modern enterprise standards strongly mandate utilizing Optional objects as method parameters and serializable class fields to maximize memory efficiency across network boundaries.
Which of the above statements is/are correct?
✅ Correct Answer: A
🎯 Quick Answer:
The correct combination is 1 and 2. Statement 3 is incorrect because the Optional class does not implement the Serializable interface and is structurally intended solely as a method return type. Using it as class fields or method parameters is widely considered a severe architectural anti-pattern that creates serialization failures and unnecessary memory overhead.It forces the caller of a method to consciously acknowledge and handle the fact that the method might not return a valid object.
Structural Breakdown: You wrap an object using Optional.of() or Optional.ofNullable(). You retrieve it using safe methods like isPresent(), ifPresent(Consumer), orElse(T), or orElseThrow(). Historical/Related Context: The inventor of the null reference, Tony Hoare, famously called it his "Billion Dollar Mistake" due to the endless system crashes it caused globally.
Java 8 introduced Optional (heavily inspired by Scala's Option monad) to structurally eliminate the ambiguity of returning null from APIs.
Causal Reasoning: The orElseGet(Supplier) method (Statement 2 context) provides a massive performance advantage over the standard orElse(T) method.
If the fallback object is computationally expensive to generate (like pulling a default profile from a slow database), orElse() evaluates it instantly regardless of whether the Optional is empty. orElseGet() defers the execution of the Supplier entirely until the JVM mathematically proves the Optional is null, saving critical resources.