DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • How to Convert XLS to XLSX in Java
  • Recurrent Workflows With Cloud Native Dapr Jobs
  • Java Virtual Threads and Scaling
  • Java’s Next Act: Native Speed for a Cloud-Native World

Trending

  • Develop a Reverse Proxy With Caching in Go
  • Unlocking AI Coding Assistants Part 1: Real-World Use Cases
  • Java's Quiet Revolution: Thriving in the Serverless Kubernetes Era
  • Evolution of Cloud Services for MCP/A2A Protocols in AI Agents
  1. DZone
  2. Coding
  3. Java
  4. Avoiding NullPointerException in Java 8

Avoiding NullPointerException in Java 8

How do you prevent NullPointerExceptions in your Java code?

By 
Amanuel G. Shiferaw user avatar
Amanuel G. Shiferaw
DZone Core CORE ·
Aug. 26, 19 · Analysis
Likes (5)
Comment
Save
Tweet
Share
43.8K Views

Join the DZone community and get the full member experience.

Join For Free

In Java, the null value can be assigned to an object reference, but accessing a null-assigned object or variable triggers the NullPointerException. First, NullPointerException is a RuntimeException.

So, how do you prevent it, you might ask? This is one of the key questions every Java developer will ask sooner or later. It's by far the most prevalent kind of error in Java, and even other programming languages as well.

In this post, we explore some simple strategies to avoid the NullPointerException. Let's get started.

NullPointerException

Different languages provide different methods for checking. Unfortunately, Java is not among them. So, we have to check our variables and objects beforehand.

Back in Java 7, there was a proposal to add a simplified method that checked for this exception. The proposal from Project Coin suggest putting ‘?.’ in every step that might throw a NullPointerException. But later, it was rejected.

Let’s look at an example:

public String getStreetName(Person person) {  
    if (person != null) {  
      Address address = person.getAddress();  
      if (address != null) {  
        return address.getStreetName();  
      }  
    }  
  return null;  
} 


Notice that we have lots of if not null checks. Assuming that we have a nested object with many fields potentially becoming null, we have to add loads of checks like the above, which, in turn, make our code difficult to read and maintain. The proposal to avoid these checks was as follows:

public String getStreetName(Person person) {
  return person?.getAddress()?.getStreetName();  
}


Prior to Java 8, things were a bit complicated. Java 8 introduced many new features among those in an “Optional” class. This is a value-based class and container object which may or may not contain a non-null value.

Let us improve the above example using Optional.

public String getStreetName(Person person) {  
    if(person == null)
      return null;
  return Optional.ofNullable(person.getAddress()).map(Address::getStreetName).orElse(null);
}


We can see how readable and safer it is to use Optional rather than a normal recursive null check. In fact, there are cases where boxing an object in Optional is meaningless. For instance, in the above code, it is enough to check if the Person object is null and exits rather than putting the object inside an Optional class to later check if it is present or not, with the isPresent() method.

Another mechanism to overcome NullPointerException might be not to check for null totally, but skip them with try...catch. Even though it might introduce confusion as the system grows, it can also be considered as a solution. Let us see an example:

public String getStreetName(Person person) {  
  try {
    return person.getAddress().getStreetName();
  }catch (NullPointerException e) {
    //NullPointer Exception raised
  } 
} 


Hope this helps!

Java (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • How to Convert XLS to XLSX in Java
  • Recurrent Workflows With Cloud Native Dapr Jobs
  • Java Virtual Threads and Scaling
  • Java’s Next Act: Native Speed for a Cloud-Native World

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!