Table of contents
1.
Introduction
2.
What is a Null Pointer Exception in Java?
3.
Reasons for the Null Pointer Exception
3.1.
1. When the Method is Invoked Using a Null Object.
3.2.
Java
3.3.
2. When a Program Tries to Modify the Null Objects Field
3.4.
Java
3.5.
3. When We Try to Pass a Null Object in a Method
3.6.
Java
3.7.
4. When We Try to Operate on a Null Array Object
3.8.
Java
3.9.
5. When We Try to Synchronise Over a Null Object
3.10.
Java
4.
Why do we need the Null Value?
4.1.
Java
5.
Avoidance of Null Pointer Exception in Java
5.1.
Method 1 - String Comparison with Literals
5.2.
Java
5.3.
Java
5.4.
Method 2 - Checking Arguments of the Method
5.5.
Java
5.6.
Method 3 - Use of Ternary Operator
5.7.
Java
6.
Frequently Asked Questions
6.1.
Should I catch a NullPointerException in Java?
6.2.
What is the best way to handle NullPointerException?
6.3.
Can we override NullPointerException in Java?
6.4.
Is NullPointerException checked or unchecked?
7.
Conclusion
Last Updated: Feb 4, 2025
Easy

Null Pointer Exception in Java

Author Aniket Majhi
1 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In Java, the Null Pointer Exception (NPE) is one of the most common runtime errors that occurs when an application attempts to use an object reference that has not been initialized, or has been set to null. This exception can happen when trying to access methods or fields of an object that doesn't point to any memory location. Understanding how and when NPE occurs is crucial for writing robust and error-free Java programs. In this blog, we’ll explore the causes of Null Pointer Exceptions, how to prevent them, and best practices for handling them in Java applications.

Null Pointer Exception in Java

What is a Null Pointer Exception in Java?

A Null Pointer Exception (NPE) in Java occurs when the JVM attempts to access or modify an object or its methods/fields through a reference that is null. This means the reference does not point to any memory location or object, leading to the exception. It commonly happens when trying to call methods or access attributes on an uninitialized object, or when a method returns null and it is improperly accessed. NPE is a runtime exception, and if not handled properly, it can cause the program to crash.

Reasons for the Null Pointer Exception

The possible scenarios where the null pointer exception can be thrown are as follows:

1. When the Method is Invoked Using a Null Object.

If we invoke some methods on the null object, Java throws the NullPointerException.

Example

  • Java

Java

public class Main{

   // returns sum of two numbers
   int sum(int a , int b) {
       return a + b;
   }
   public static void main(String[] args) {
       Main m = null;  // intitialised the object with null value
       // Invoking the method sum on the null object.
       System.out.println(m.sum(10, 20));
   }
}
You can also try this code with Online Java Compiler
Run Code

Output

Practice by yourself on java online compiler.

2. When a Program Tries to Modify the Null Objects Field

If any program tries to modify the null object field, the NullPointerException is thrown.

Example

  • Java

Java

public class Main{
   int val = 10;
   public static void main(String[] args) {
       Main m = null;  // intitialised the object with null value
       // It tries to read the data on the null object
       System.out.println(m.val);
   }
}
You can also try this code with Online Java Compiler
Run Code

Output


Also see,  Swap Function in Java

3. When We Try to Pass a Null Object in a Method

If we try to pass the null object field in a method, the NullPointerException is invoked.

Example

  • Java

Java

public class Main{

   // the java integer class in given here
   int meth(Integer x){
       return x.intValue();
   }

   public static void main(String[] args) {
       // creating a the object m
       Main m = new Main();

       // trying to invoke the method using the null parameter
       System.out.println(m.meth(null));

   }
}
You can also try this code with Online Java Compiler
Run Code

Output

4. When We Try to Operate on a Null Array Object

If we try to operate on a null array object, this type of NullPointerException will be thrown.

Example

  • Java

Java

public class Main{
   // The array arr is set to null
   int arr[] = null;
   public static void main(String[] args) {

       // a object m of type Main is created
       Main m = new Main();

       // trying to print the lenght of the null array
       System.out.println(m.arr.length);

   }
}
You can also try this code with Online Java Compiler
Run Code

Output

5. When We Try to Synchronise Over a Null Object

When we try to synchronise over a null object, if the object reference for the synchronisation is null, then the NullPointerException is thrown.

Example

  • Java

Java

public class Main{
   // The static variable val of type String is set to null
   public static String val = null;
   public static void main(String[] args) {

       // Trying to enter to the synchronized block by using val
       synchronized(val) {
           System.out.println("Synchronized");
       }

   }
}
You can also try this code with Online Java Compiler
Run Code

Output

Why do we need the Null Value?

In Java, null represents the absence of a value or an uninitialized object reference. It helps handle optional data, avoid unnecessary object creation, and indicate missing values in collections or APIs. However, improper handling can lead to NullPointerException.

Example:

  • Java

Java

class Student {
String name;
}

public class Main {
public static void main(String[] args) {
Student student = null; // No object assigned
if (student == null) {
System.out.println("Student object is null");
}
}
}
You can also try this code with Online Java Compiler
Run Code

 

Output:

Student object is null

Avoidance of Null Pointer Exception in Java

For Java developers, avoidance of the NullPointerException is an important task. Unlike other programming languages, Java does not provide any method to check for NullPointerException.

To avoid the null pointer exceptions, you need to ensure that every object must be initialised with some value before you use them.

We can consider the following scenarios to deal with the NullPointerException.

Method 1 - String Comparison with Literals

In this case, we compare a string to a literal.

If the String object is set to null, it throws a NullPointerException, as shown below.

Example1

  • Java

Java

public class Main{
   public static void main(String[] args) {
       // the string value is initialized to null
       String s = null;
       try{
           // we are checking if the string is equal to "hello" or not
          // if the string is found to be null, then the  NullpointerException will be thrown
           if(s.equals("hello")) {
               System.out.println("The string is \"hello\"");
           }
           else{
               System.out.println("The string is not \"hello\"");
           }
       }
       catch(NullPointerException e){
           System.out.println("NullpointerException");
       }
   }
}
You can also try this code with Online Java Compiler
Run Code

Output1

We can avoid this null pointer exception by invoking the equals() method from the literal.

Let’s see how we can do this in the below example.

Example2

  • Java

Java

public class Main{
   public static void main(String[] args) {
       // the string value is initialized to null
       String s = null;
       try{
           // we are checking if the string is equal to "hello" or not, by invoking the equals method from the literal "hello"
           if("hello".equals(s)) {
               System.out.println("The string is \"hello\"");
           }
           else{
               System.out.println("The string is not \"hello\"");
           }
       }
   
       catch(NullPointerException e){
           System.out.println("NullpointerException");
       }
   }
}
You can also try this code with Online Java Compiler
Run Code

Output2

Method 2 - Checking Arguments of the Method

Here, we check the arguments passed to a method for null values. If the arguments are properly checked, then only we execute the body of the function. However, if the arguments are not legitimate, it throws an IllegalArgumentException.

Example

  • Java

Java

public class Main{
   // method getString() returns the string argument
   public static String getString(String s) {
       // if the string is null it informs the calling method that the argument is illegal.
       if(s == null)
       throw new IllegalArgumentException("The argument is null");
       return s;
   }
   public static void main(String[] args) {

       String s = null;
       try{
           // It throws an IllegalArgumentException
           System.out.println(getString(s));
       }
       catch(IllegalArgumentException e) {
           System.out.println("IllegalArgumentException");
       }

       s = "Hello there!";

       try{
           // It prints the string
           System.out.println(getString(s));
       }
       catch(IllegalArgumentException e) {
           System.out.println("IllegalArgumentException");
       }

   }
}
You can also try this code with Online Java Compiler
Run Code

Output

Method 3 - Use of Ternary Operator

We can also use the ternary operator to avoid the NullPointerException. Using the ternary operator, we first check the boolean expression, and if it is found to be true, then the first value will be returned. Otherwise, the second value will be returned.

Example

  • Java

Java

public class Main{
   public static void main(String[] args) {
       String s = null;

       // as s == null, it initializes the variable with the empty string
       String ans = (s == null) ? "" : s;
       System.out.println(ans);

       // as the s != null, it initializes the variable the variable with the whole string.
       s = "hello there";
       ans = (s == null) ? "" : s;
       System.out.println(ans);
   }
}
You can also try this code with Online Java Compiler
Run Code

Output

 Also see, Hashcode Method in Java  

Frequently Asked Questions

Should I catch a NullPointerException in Java?

Catching a NullPointerException is generally not recommended; instead, focus on preventing it through proper null checks, initialization, and safe method calls.

What is the best way to handle NullPointerException?

The best way to handle a NullPointerException is to prevent it by checking for null values, using Optional, and applying defensive programming practices.

Can we override NullPointerException in Java?

No, we cannot override NullPointerException, but we can handle it using a try-catch block. Since it extends RuntimeException, we can create a custom exception by extending it, but overriding system-defined exceptions is not possible.

Is NullPointerException checked or unchecked?

NullPointerException is an unchecked exception because it extends RuntimeException. It is not checked at compile-time, meaning the compiler does not force handling it. It occurs at runtime when an application attempts to use null where an object is required.

Conclusion

NullPointerException in Java is a common runtime exception that occurs when an application attempts to access an object reference that is null. It is an unchecked exception, meaning it is not enforced at compile time. Proper handling of null values using null checks, Optional class, or exception handling can help prevent unexpected crashes.

Live masterclass