Thursday, September 28, 2023

How to deal with NullPointerException in Java with Examples - java.lang.NullPointerException Guide

The java.lang.NullPointerException or NullPointerException in Java is probably the first error or exception you will face in Java. It is a true nightmare for beginners in Java but pretty easy to solve once you get familiar with Exception handling in Java. What makes NullPointerException a little bit tricky to solve is its name which has a pointer in itself and Java does not support pointers like C++ or C, just like you don't have multiple inheritances in Java. As a Java developer with 20 years of experience, I have solved countless amount of NullPointerException and now I have developed a coding and debugging sense through which I can spot what causing a particular NullPointerException and how to fix it. 

In this article, I am sharing that experience with you as you will learn everything about NullPointerException in Java right from what is NullPointerException in Java, How to solve Exceptions in thread "main" java.lang.NullPointerException, finding the possible cause of Java NullPointerException and how to troubleshoot NPE in Java.

Based on my experience once you know a little bit about NullPointerException it's pretty easy to solve. By the way, as said, "prevention is better than cure", you can avoid != null check and NullPointerException by following some best practices.

java.lang.NullPointerException - Common Cause of NullPointerException in Java Example



What is NullPointerException in Java?

NullPointerException in Java is nothing but an error or precisely an exception that occurs if we tried to perform any operation on an object which is null. 

In Java reference variable points to object created in heap but when you create a reference variable of type object by default its points to "null" and when you try to call any method on null, try to access any variable on null you will get this null pointer exception.

No matter by what reason your reference variable is pointing to null be it not initialized or set to null if you perform any operation it will throw Exception in thread main : java.lang.NullPointerException



When does NullPointerException occurs in Java?

Javadoc of java.lang.NullPointerException has outlined scenario when it could occur:

1) When you call the instance method on a null object. you won't get a null pointer exception if you call a static method or class method on the null object because the static method doesn't require an instance to call any method.

2) While accessing or changing any variable or field on a null object.

3) Throwing null when an Exception is expected to throw.

4) When getting the length of an array when the array is null.

5) Accessing or changing slots of null just like an array.

6) When you try to synchronize on a null object or using null inside the synchronized block in Java.

Now, we will see examples of NullPointerException for each of the above scenarios to get it right and understand it better. You can also see these free Java programming courses to learn more about NullPointerException in Java. 




Common Reasons of NullPointerException in Java as Example

Based upon my experience java.lang.NullPointerException repeats itself in various formats, I have collected the most common cause of java.lang.NullPointerException in java code and explained them here, we will use the following Trade class for example :

public class Trade {
   
private String symbol;
   
private int price;
   
public static String market;

   
public Trade(String symbol, int price) {
       
this.symbol = symbol;
       
this.price = price;
   
}

   
public int getPrice() {
       
return price;
   
}

   
public void setPrice(int price) {
       
this.price = price;
   
}

   
public String getSymbol() {
       
return symbol;
   
}

   
public void setSymbol(String symbol) {
       
this.symbol = symbol;
   
}

}


1. Java  NullPointerException while calling instance method on null object

This is probably the most common cause of this error, you call method on some object and found that the reference is null, always perform null check if you see possibility of null before calling any method on object.

Trade pennyStock = null;
pennyStock.getPrice(); //this will throw NullPointerException

Exception in thread "main" java.lang.NullPointerException
at test.NullPointerExceptionTest.main(NullPointerExceptionTest.java:23)



2. NullPointerException in Java while accessing field on a null reference.


Trade fxtrade = null;
int price = fxtrade.price; //here fxtrade is null, you can’t access field here

Exception in thread "main" java.lang.NullPointerException
at test.NullPointerExceptionTest.main(NullPointerExceptionTest.java:64)


3. java.lang.NullPointerException when throwing null as an exception.

If you throw an Exception object and if that is null you will get a null pointer exception as shown in the below example

RuntimeException nullException = null;
throw nullException;

Exception in thread "main" java.lang.NullPointerException
at test.NullPointerExceptionTest.main(NullPointerExceptionTest.java:74)


4. example of NullPointerException is when getting the length of an array that is null.

Trade[] bluechips = null;
int length = bluechips.length;  //array is null here

Exception in thread "main" java.lang.NullPointerException
at test.NullPointerExceptionTest.main(NullPointerExceptionTest.java:85)


5. Example of NPE when accessing an element of a null array.

Trade[] bluechips = null;
Trade motorola = bluechips[0]; //array is null here

Exception in thread "main" java.lang.NullPointerException
at test.NullPointerExceptionTest.main(NullPointerExceptionTest.java:94)


6. You will also get NullPointerException in Java if you try to synchronize on a null object or try to use the null object inside the synchronized block in Java.

Trade highbetaTrade = null;
synchronized(highbetaTrade){
System.out.print("This statement is synchronized on null");
}

Exception in thread "main" java.lang.NullPointerException
at test.NullPointerExceptionTest.main(NullPointerExceptionTest.java:104)




How to solve NullPointerException in Java

To solve a NullPointerException in Java first we need to find the root cause, which is very easy just look at the stack-trace of NullPointerException and it will show the exact line number where NPE has occurred. 

Now go to that line and look for possible object operations like accessing the field, calling method or throwing exception etc, that will give you an idea of which object is null. Now once you found that which object is null job is half done, now find out why that object is null and solve the java.lang.NullPointerException

This second part always very sometimes you get null object from the factory or sometimes some other thread might have set it null, though using Assertion in early phase of development you can minimize the chances of java.lang.NullPointerException but as I said its little bit related to the environment and can come on production even if tested fine in test environment.

It's best to avoid NullPointerException by applying careful or defensive coding techniques and null-safe API methods.


When in Java Code NullPointerException doesn't come

1) When you access any static method or static variable with null reference.
If you are dealing with static variables or static methods then you won't get a null pointer exception even if you have your reference variable pointing to null because static variables and method calls are bonded during compile time based on the class name and not associated with an object. 

For example below code will run fine and not throw NullPointerException because "market" is an static variable inside Trade Class.

Trade lowBetaTrade = null;
String market = lowBetaTrade.market; //no NullPointerException market is static variable




Important points on NullPointerException in Java

1) NullPointerException is an unchecked exception because it extends RuntimeException and it doesn’t mandate try-catch block to handle it.

2) When you get NullPointerException to look at the line number to find out which object is null, it may be an object which is calling any method.

3) Modern IDE like NetBeans and Eclipse gives you the hyperlink of the line where NullPointerException occurs

4) You can set an Exception break point in Eclipse to suspend execution when NullPointerException occurs read 10 tips on java debugging in Eclipse for more details.

5) Don't forget to see the name of Thread on which NullPointerException occurs. in multi-threading, NPE can be a little tricky if some random thread is setting a reference to null.

6) It's best to avoid NullPointerException while coding by following some coding best practices or putting a null check on the database as a constraint.

That’s all on What is java.lang.NullPointerException, When it comes, and how to solve it. In the next part of this tutorial, we will look at some best java coding practices to avoid NullPointerException in Java.


Other Java debugging tutorial

Thanks for reading this article so far. If you like my tips and explanation then please share this article in social media. If you have any question or feedback or struggling with NullPointerException then please paste your error in comments and I will try to help you out. 

25 comments:

  1. I like the way you presented common scenario where NullPointerException can appear but how about fixing those issues. This is one error which I hate and love to fix them well before they occur. Is there any coding practice, design pattern or guideline exists to avoid NullPointerExcepiton completely ?

    ReplyDelete
  2. What is NullPointerException in Java ? I heard there is no pointer in Java than How come you got NulllPointer ?

    ReplyDelete
  3. What is the best way to handle NullPointerException in Java ? Is it best to avoid NullPointerException or handle it ? Should I always perform null check before calling any method or accessing any field ? These null check are making my code dirty, I would love to remove those null check but at same time I don't want my program die because of incomplete data. Please suggest proper way of handling NullPointerException in Java.

    ReplyDelete
  4. Hi I am getting NullPointerException in my homework excercise, which is to filterNames which doesn't have surnmae :

    Exception in thread "main" java.lang.NullPointerException
    at Homework2.hasSurname(Homework2.java:38)
    at Homework2.filterNames(Homework2.java:32)
    at Homework2.main(Homework2.java:23)

    ReplyDelete
  5. Looks like you are passing null to hasSurname() method, can you post your code here?

    ReplyDelete
  6. To the earlier poster asking "What is the best way to handle NullPointerException in Java?" .. you need to fix your code. It is not appropriate to catch NullPointerException because it can only happen when there's a bug in your code -- you need to fix the bug.

    ReplyDelete
  7. Post Java 5, Another common cause of NullPointerException is Autoboxing. Autoboxing will throw NullPointerException, if you convert an Integer null instance to int primitive. This kind of bugs are really hard to find. Consider this code :

    public int getFrequency(String band){
    return transmitter.get(band);
    }
    here transmitter is a Map, which holds String as band and Integer as frequency, this will throw NullPointerException, if there is no value for corresponding band,and believe me it's really hard to find.

    ReplyDelete
  8. Another cause for NPE is due to autoboxing while we retrieve results from the table.

    ReplyDelete
  9. @Mrlon and @I @m The W@y I @M, you are right, any method which is supposed to return int but returning Integer can fail miserably with java.lang.NullPointerException, if return value is null. I have recently faced this where one of my method is returning value from a HashMap, something like this :

    public int getCount(Item item){
    return inventory.get(item);
    }

    where inventory was a HashMap which stores item counts, an Integer. Can be really tricky, if you are not careful with Autoboxing.

    ReplyDelete
  10. What is java lang NullPointerException in Java ? I heard there is no pointer in Java than How come you got NulllPointer

    ReplyDelete
  11. @Wajid, NullPointerException has nothing to do with pointers of C++. It's true that Java doesn't have pointers, as it doesn't allow you to manipulate memory location directly, but they have reference variables and objects. One value object can have is null, which is also default value of an object, when created. If you happen to call any method or access any field on null object, then you will get NullPointerException in Java.

    ReplyDelete
  12. This is the first article, which help me to understand NullPointerException, and provides clear guidelines to solve java.lang.NullPointerException. Most of articles says that something is null, well YES, I know something is null, but what is null, How to find that null and then What to do after got to the code, which is throwing this exception, was something I wanted to understand. Thanks to author for helping developers out here.

    ReplyDelete
  13. One of the major cause of NullPointerException in Java is that many programmer forget to handle null. Sometime they don't read Javadoc and missed the point that the method they are calling can return null. Though I agree that, a method should not return null, if possible it return a default value e.g. an Empty object like empty String, empty collection or Java 8's Optional value, which indicate they value can be absent and ensure that caller of method code for the case when value is not present in Optional. Apart from that you can use the tips mentioned in the linked article avoid NullPointerException in Java

    ReplyDelete
  14. I am getting runtime error (Null Pointer exception) while using .equals method with string array..
    Please Tell what to do???

    ReplyDelete
  15. Hello @kislaya, Can you post your code? Most likely you have null in your String array which is causing when calling equals() method. Depending upon your code, we may be able to reverse the order of equals() to fix this NullPointerException.

    ReplyDelete
  16. Javin Paul Here is my code...--->

    import java.io.*;
    public class Abc {
    public static void main(String[] args) throws IOException {
    InputStreamReader read = new InputStreamReader(System.in);
    BufferedReader inp = new BufferedReader(read);
    int T=Integer.parseInt(inp.readLine());
    for(int x=0;x3){
    System.out.println("YES");
    break;
    }
    else if(k==3){
    if(((Sa[4].equals(Sa[2]))&&(Sa[4].equals(Sa[0])))||((Sa[4].equals(Sa[2]))&&(Sa[4].equals(Sa[1])))||((Sa[4].equals(Sa[3]))&&(Sa[4].equals(Sa[0])))||((Sa[4].equals(Sa[3]))&&(Sa[4].equals(Sa[1])))||((Sa[5].equals(Sa[2]))&&(Sa[5].equals(Sa[0])))||((Sa[5].equals(Sa[2]))&&(Sa[5].equals(Sa[1])))||((Sa[5].equals(Sa[3]))&&(Sa[5].equals(Sa[0])))||((Sa[5].equals(Sa[3]))&&(Sa[5].equals(Sa[1]))))
    System.out.println("YES");
    break;
    }
    else if(k<3)
    System.out.println("NO");
    }
    }
    }

    ReplyDelete
  17. Javin I have run my code on ideone.com(online complier)..It is showing NullPointerException....
    Please Help me out....

    ReplyDelete
  18. My code is not visible ...Why???

    ReplyDelete
  19. Hello kislaya, What is Sa[] in your code, I don't see declaration for it. You can post the link of ideone where you have written your code.

    ReplyDelete
  20. do one thing, first loop through your array Sa and throw IllegalArgumentException if it contains null. I still think that full code is not here as I don't know how that array is getting populated, without that helping is little bit difficult.

    alternatively you can replace null with empty string in your array while iterating if your logic allows it.

    ReplyDelete
  21. I have this loop to fill String Array.....


    for(int i=0;i<Sa.length;i++){
    Sa[i]=inp.readLine();
    Sc[i]=Sa[i];
    }

    ReplyDelete
  22. In the loop before adding check for null e.g.

    String line = inp.readLine()
    if(line != null){
    Sa[i] = line;
    }else {
    System.out.println( i + "th line is : "+ line);
    }

    readLine() method returns null if there is no more line to read, which is actually the case after last line.

    ReplyDelete
  23. In our project, the most common cause of NullPointerException was incorrect use of autoboxing e.g. passing double, int, float or long to methods which accepts Double, Integer, Float or Long.

    Consider this code:

    bean.setPrice(order.getPrice());

    now, if setPrice expect a double and getPrice() return a Double that it can cause java.lang.NullPointerException if getPrice() return null.

    just try this

    Integer i = null;
    int j = i; // this will throw NullPointerException

    ReplyDelete
  24. Another common cause of NullPointerException is in JDBC code, where you set the parameter for calling stored procedure using CallableStatement or setting placeholders while using PreparedStatement in Java, and the root cause there too is autoboxing.

    Consider following SQL query

    PreparedStatement ps = connection.prepareStatement("SELECT * FROM Books WHERE Edition=?);
    ps.setInt(1, book.getEdition());

    now if this getEdition() returns null then you will get NullPointerException, even though your column might allow null.

    correct way to set null in JDBC is
    ps.setNull(1, Types.INTEGER)

    many Java developer make this mistake while mapping database column to object properties in JDBC and pay price later.

    ReplyDelete
  25. java.lang.NullPointerException what hepan this]

    ReplyDelete