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
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Stop Writing Database Migration Scripts: Declarative Schema Sync for Java
  • Searching Kafka Without an Index: Lessons From Building Message Search for Kafdrop
  • ScyllaDB in Enterprise Java: High-Performance NoSQL With Eclipse JNoSQL
  • Member Spotlight: Shai Almong

Trending

  • Genkit Flows as senro Steps: Extremely Powerful AI Pipelines in Go
  • How an AI Software Factory Works: From Developer Intent to Production
  • The Three Tiers of Agentic Incident Response: When to Trust AI Autonomy
  • PWA on iOS, Part 2: HTTPS, Manifest and Service Worker

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  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
·
Aug. 26, 19 · Analysis
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
44.6K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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

  • Stop Writing Database Migration Scripts: Declarative Schema Sync for Java
  • Searching Kafka Without an Index: Lessons From Building Message Search for Kafdrop
  • ScyllaDB in Enterprise Java: High-Performance NoSQL With Eclipse JNoSQL
  • Member Spotlight: Shai Almong

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • 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