Thursday, April 20, 2023

How to deal with java.lang.NullPointerExceptionin Java? Cause, Solution, and Tips to avoid NPE

Hello Java programmers, if you want to learn what is NullPointerExcpeiton in Java and how to deal with NullPointerException or NPE then you have come to the right place. NullPointerException in Java is an unchecked Exception defined in java.lang package and comes when a member of an object either field or method is called on an object which is null. null is a keyword in Java that means nothing and the calling method on an object whose value is null will result in NullPointerException. Since the default value of Object is null, if you call any method or access any field on an Object which is not initialized will throw NullPointerException

Some programmers get confused with name as well, Since Java does not support pointers, how can you have NullPointerException in Java?

Well, java.lang.NullPointerException doesn't have anything to do with pointers, it just an Exception in Java. If you look at it more deeply, NullPointerException is an unchecked Exception and it's not mandatory to provide Exception handling code for it using try, catch, and finally.


In fact, most of NullPointerException comes because of programming errors. See the most common cause of NullPointerException to find out the most common scenario where NullPointerException comes in Java. 

In this Java article, we will not only see what is NullPointerException but also How to avoid NullPointerException and how to fix java.lang.NullPointerException in Java.





When does NullPointerException occur in Java?

In the last section, you have learned what it is java.lang.NullPointerException and finds that NullPointerException occurs when we call a method or access members on an Object which is null, I mean, either it's not initialized or it has been set null explicitly. 

This is fundamental of NullPointerException but it manifest itself in many places like

1) NullPointerException comes when you try to use an Object in the synchronized keyword which is null as shown in the following example :

Object lock = null;
synchronized(lock){ } //NullPointerException, can not synchronized with null object


2) Similarly, if you try to access an element from Array, which is null will result in NullPointerException.

The key challenge is always to find which reference variable is null and that's where experience comes into play, Once you have some experience dealing with NullPointerException you can easily figure out which object or reference variable is null by looking at the stack trace of the error message. 

Oracle is also working on a feature that could give more information about NullPointerException like which reference variable is null that will help immensely to solve this problem but until that feature comes, you need to know details to troubleshoot this common Java issue. 

As I have also suggested, joining a comprehensive Java course like Java Programming for Complete Beginners - Java 16 can also help to better understand core concepts of Java and troubleshoot common Java errors like NullPointerExcepiton, NoClassDefFoundError, and ClassNotFoundException. 

How to solve NullPointerException in Java [Tips]




How to solve NullPointerException in Java?

What is NullPointerExcpetion in Java When Why HowOnce you understand that NullPointerException occurs because an operation is performed with a null object like accessing a field or calling a method or comparing with something, your next task is to find out which object is null and you can do that by looking at the stack trace of NullPointerException

Since the most common cause of NullPointerException is that reference variable pointing to null instead of a valid object reference. 

Let's see an example of NullPointerException in Java :

/**
 *
 * Java program to demonstrate when NullPointerException occurs and
 * How to fix NullPointerException in Java
 *
 * @author java67
 */

public class Hello {

    private static String name;
 
    public static void main(String args[]){
     
        if(name.equals("Java")){
            System.err.println("Welcome to Java");
        }
    }
}

Exception in thread "main" java.lang.NullPointerException
        at test.CollectionTest.main(CollectionTest.java:18)


Troubleshooting of NullPointerExcpetion in Java

Now by looking at the output and stack trace of this program we know that error occurred at line 18, where we are comparing the name member variable to the String literal "Java", I mean we have code like name.equals("Java"). Since the name is not initialized anywhere in the program and it's a String Object, it contains the default value null, which is causing this NullPointerException

To avoid this NullPointerException we can do two things

1) First do a null check like the name != null before calling any method on that

2) We can use the fact that the equals method returns false if we compare it will null e.g. if we write code like "java".equals(name) we will not get any NullPointerException, instead, it will return false.

That's all about How to deal with NullPointerException in Java. In this Java tutorial, you have learned what is NullPointerException in Java, when does NullPointerException occur in Java, and how to solve NullPointerException in Java

In Summary, try to avoid NullPointerException by making sure you follow the contract is like using an object when it's initialized, and by defensive coding. You can also write null safe method likes equals() if you don't trust your client to avoid NullPointerException in Java.


Other Java fundamental tutorials from java67

Thanks for reading this article so far. If you find this Java NullPointerExetpion tutorial useful and these tips useful then please share with your friends and colleagues. If you have any questions or feedback then please drop a note. 

P. S. - If you are new to the Java world and looking for a free online course to learn Java then you can also check out this Java Tutorial for Complete Beginners (FREE) course on Udemy. More than 1.2 million programmers have already joined this course to learn Java online for FREE. 

P. P. S. - If you are getting NullPointerExcpetion in your Java program and not able to solve it then you can also post your code and error message here and we can solve them together. This can also add few more real-life examples of NullPointerException for Java programmers and help them to better understand and solve on their own. 

2 comments:

  1. Adding null in Java programming language is biggest mistake by Java designer, They should have provided better default value like empty and should not be allowed to fail application by programming language itself just like many scripting language e.g python or perl do.

    ReplyDelete
  2. can u explain it in better way with best example

    ReplyDelete

Feel free to comment, ask questions if you have any doubt.