Logo

dev-resources.site

for different kinds of informations.

Handling NullPointerException with Optional

Published at
12/26/2024
Categories
webdev
springboot
java
designpatterns
Author
parzival_computer
Author
17 person written this
parzival_computer
open
Handling NullPointerException with Optional

Definition

NPE is a runtime exception that occurs when trying to use a null reference. The JVM throws this exception to protect against dereferencing null pointers, which could cause program crashes.

Common Causes

Basic Example

String name = null;
int length = name.length(); // NPE thrown here
Enter fullscreen mode Exit fullscreen mode

Here, we're trying to call a method on a null reference. The variable name contains no object, so we can't invoke length().

Nested Objects Example

class User {
    Address address;
}
class Address {
    String street;
}

User user = new User();
String street = user.address.street; // NPE: address is null
Enter fullscreen mode Exit fullscreen mode

This shows how nested object access can fail. While user exists, address is null because we haven't initialized it.

Collection Example

List<String> items = null;
items.add("item"); // NPE
Enter fullscreen mode Exit fullscreen mode

Collections should be initialized before use. Better to initialize as empty: List<String> items = new ArrayList<>();

Optional Usage Explained

Basic Optional Chaining

Optional<User> user = Optional.of(new User());
String street = user
    .flatMap(User::getAddress)  // Converts User to Optional<Address>
    .map(Address::getStreet)    // Converts Address to Optional<String>
    .orElse("Unknown");         // Provides default if null
Enter fullscreen mode Exit fullscreen mode

This replaces nested null checks with a fluent API. Each step safely handles potential nulls.

Map and Filter

Optional<String> upperStreet = Optional.ofNullable(user)
    .filter(u -> u.getName() != null)  // Only proceed if name exists
    .map(User::getName)                // Get the name
    .map(String::toUpperCase);         // Transform it
Enter fullscreen mode Exit fullscreen mode

This shows how to transform values while handling nulls safely.

Default Values

String result = Optional.ofNullable(someString)
    .orElse("default");
Enter fullscreen mode Exit fullscreen mode

A clean way to provide fallback values instead of null checks.

Conditional Execution

Optional.ofNullable(user)
    .ifPresent(u -> System.out.println(u.getName()));
Enter fullscreen mode Exit fullscreen mode

Execute code only when the value exists, replacing if-not-null checks.

springboot Article's
30 articles in total
Favicon
Launched a Web version of my Project using Java Spring Framework, Spring Boot Web
Favicon
Understanding Spring Security and OAuth 2.0
Favicon
Spring Oauth2 - App-Token based Hybrid Token Verification Methods
Favicon
Static variables in Java
Favicon
What is Spring AI ? Example of a chat API with multiple LLMs
Favicon
Quando usar ResponseEntity?
Favicon
App-Token based easy OAuth2 implementation built to grow with Spring Boot
Favicon
[Boost]
Favicon
Spring Boot 3 application on AWS Lambda - Part 14 Measuring cold and warm starts with GraalVM Native Image and memory settings
Favicon
SpringBoot Web Service - Part 5 - Github Action
Favicon
Apache wicket with spring boot example application: notice board
Favicon
OTP Authentication: The Passwordless Superhero of Your App! πŸ¦Έβ€β™‚οΈβœ¨
Favicon
SpringBoot Web Service - Part 1 - Create Repository
Favicon
SpringBoot Web Service - Part 2 - Preparing Using Spring Initializr
Favicon
Zero Config Spring Batch: Just Write Business Logic
Favicon
Generate a REST API Using Java and Spring Boot for your Postgres database
Favicon
How to optimize SpringBoot startup
Favicon
Spring Boot: About @SpringBootApplication
Favicon
Introduction to Spring Boot: A Complete Guide
Favicon
Wednesday Links - Edition 2025-01-01πŸŽ‰
Favicon
SpringBoot Web Service - Part 4 - Initial Configuration
Favicon
How to implement detekt in Spring Boot + Kotlin + Gradle project
Favicon
Building Resilient APIs: Mistakes I Made and How I Overcame Them
Favicon
Web Scraping Summarization with Vite React TypeScript and Spring Boot
Favicon
Handling NullPointerException with Optional
Favicon
Overview of Lock API in java
Favicon
Optimizing Serverless Lambda with GraalVM Native Image
Favicon
With Spring can I make an optional path variable?
Favicon
Building a Vue CRUD App with a Spring Boot API
Favicon
Hexagonal Architecture β€” A Favorite Lyrics Spring Boot β€” Java Example

Featured ones: