Java Interview Question: What is Optional in Java 8? How to Avoid NullPointerException (With Examples)
🔹 Introduction
Handling null values is one of the biggest challenges in Java.
👉 A very common interview question is:
“What is Optional in Java and how does it help avoid NullPointerException?”
🔹 What is Optional?
Optional is a container object introduced in Java 8.
👉 It is used to:
- Represent a value that may or may not be present
-
Avoid
NullPointerException
🔹 Why Do We Need Optional?
Before Java 8:
String name = null;
System.out.println(name.length()); // NullPointerException
👉 This causes runtime error ❌
🔹 Using Optional
import java.util.Optional;
public class Test {
public static void main(String[] args) {
Optional<String> name = Optional.ofNullable(null);
System.out.println(name.orElse("Default Name"));
}
}
🔹 Output
Default Name
🔍 Important Methods of Optional
🔹 of()
Optional<String> name = Optional.of("Java");
👉 Throws exception if null
🔹 ofNullable()
Optional<String> name = Optional.ofNullable(null);
👉 Safe way
🔹 isPresent()
if (name.isPresent()) {
System.out.println(name.get());
}
🔹 orElse()
System.out.println(name.orElse("Default"));
🔹 orElseGet()
System.out.println(name.orElseGet(() -> "Generated Value"));
🔹 orElseThrow()
name.orElseThrow(() -> new RuntimeException("Value not present"));
🔹 Real Interview Scenario
👉 Returning Optional from method:
public Optional<String> getName() {
return Optional.ofNullable(null);
}
🔹 When to Use Optional?
✔ Method return type
✔ Avoid null checks
✔ Functional programming
⚠️ When NOT to Use
❌ Fields in entity
❌ Method parameters
❌ Serialization
🔹 Time Complexity
- O(1)
🔹 Key Takeaways
✔ Optional avoids NullPointerException
✔ Improves readability
✔ Encourages functional style
✔ Frequently asked interview question
🔹 Conclusion
Optional is a powerful feature in Java 8 that helps write cleaner and safer code by avoiding null-related issues.
Comments
Post a Comment