NullPointerException is the most common runtime error in Java. Often the cause is simple: a method returned null, and the caller forgot to check. Optional, added in Java 8, makes “there may be no value” visible in the method signature.
Creating an Optional
Optional.of(value): when the value is definitely not null.Optional.ofNullable(value): when it might be null.Optional.empty(): when there is no value.
Spring Data repositories already return Optional: courseRepository.findById(id) gives Optional<Course>.
Reading it safely
orElse(defaultValue): use a fallback when empty.orElseGet(() -> createDefault()): build the fallback only when needed.orElseThrow(() -> new CourseNotFoundException(id)): fail with a clear error, the common choice in REST APIs.ifPresent(c -> System.out.println(c.getTitle())): run code only when a value exists.
Transforming values
map() changes the value inside if it exists: findById(id).map(Course::getTitle).orElse("Unknown"). filter() keeps it only if a condition holds. These chain neatly with lambdas.
Mistakes to avoid
- Calling
get()without checking. It throws an exception on an empty Optional, which just moves the problem. - Using Optional for fields or method parameters. It is designed for return values.
- Returning null from a method declared to return Optional. Return
Optional.empty()instead. - Wrapping collections. Return an empty list rather than
Optional<List>.
Interview angle
Be ready to explain why Optional exists, the difference between orElse and orElseGet, and how you used it with Spring Data in a project.
Related: lambda expressions in Java, Java streams and Spring Boot exception handling.
These topics are practised with projects and mock interviews in our Java Full Stack course in Bangalore.
Book a free demo class at our BTM Layout centre, and ask a counsellor for batch details.
