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
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Getting Started With Agentic Workflows in Java and Quarkus
  • Building AI-Powered Java Applications With Jakarta EE and LangChain4j
  • Alternative Structured Concurrency
  • Jakarta EE 12: Entering the Data Age of Enterprise Java

Trending

  • Exactly-Once Processing: Myth vs Reality
  • How to Format Articles for DZone
  • Detecting Bugs and Vulnerabilities in Java With SonarQube
  • A Deep Dive into Tracing Agentic Workflows (Part 1)
  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
·
Aug. 26, 19 · Analysis
Likes (5)
Comment
Save
Tweet
Share
44.3K 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

  • Getting Started With Agentic Workflows in Java and Quarkus
  • Building AI-Powered Java Applications With Jakarta EE and LangChain4j
  • Alternative Structured Concurrency
  • Jakarta EE 12: Entering the Data Age of Enterprise Java

Partner Resources

×

Comments

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

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

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 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook