Table of contents
1.
Introduction
2.
What is a Null Pointer Exception in Java?
3.
Possible Scenarios for the Null Pointer Exception
3.1.
When the Method is Invoked Using a Null Object.
3.1.1.
Example
3.2.
Java
3.2.1.
Output
3.3.
When a Program Tries to Modify the Null Objects Field
3.3.1.
Example
3.4.
Java
3.4.1.
Output
3.5.
When We Try to Pass a Null Object in a Method
3.5.1.
Example
3.6.
Java
3.6.1.
Output
3.7.
When We Try to Operate on a Null Array Object
3.7.1.
Example
3.8.
Java
3.8.1.
Output
3.9.
When We Try to Synchronise Over a Null Object
3.9.1.
Example
3.10.
Java
3.10.1.
Output
4.
Avoidance of Null Pointer Exception in Java
4.1.
Scenario1(String Comparison with Literals)
4.1.1.
Example1
4.2.
Java
4.2.1.
Output1
4.2.2.
Example2
4.3.
Java
4.3.1.
Output2
4.4.
Scenario2(Checking Arguments of the Method)
4.4.1.
Example
4.5.
Java
4.5.1.
Output
4.6.
Scenario3(Use of Ternary Operator)
4.6.1.
Example
4.7.
Java
4.7.1.
Output
5.
Frequently Asked Questions
5.1.
What is NullPointerException caused by?
5.2.
How do I fix NullPointerException in Java?
5.3.
Should I catch a NullPointerException in Java?
5.4.
What is the best way to handle NullPointerException?
6.
Conclusion
Last Updated: Nov 6, 2024
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.

Possible Scenarios for the Null Pointer Exception

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

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.

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

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

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

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

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.

Scenario1(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

Scenario2(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

Scenario3(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

What is NullPointerException caused by?

A NullPointerException is caused when an application attempts to use a null reference to access methods, fields, or elements of an object.

How do I fix NullPointerException in Java?

Fix a NullPointerException by ensuring that references are properly initialized, checking for null before accessing methods/fields, and using Optional where appropriate.

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.

Conclusion

In this article, we have extensively discussed the Null Pointer Exception in Java.

We started with the basic introduction of the blog. we coved some of the important key points:- 

  • What is the Null Pointer Exception in Java
  • The cases in which we can get the Null pointer Exception
  • We discussed five cases.
    • The method is invoked with null objects.
    • The program tries to modify the null object.
    • A null object is passed to the method.
    • Operate on the null array object.
    • Synchronise over a null object.
  • Avoidance of the Null Pointer Exception.
  • We discussed three different scenarios, string comparisonchecking arguments and use of the ternary operators.

We hope that this blog has helped you enhance your knowledge regarding Null Pointer Exception in Java and if you would like to learn more, check out our articles on Converting Java String to IntChar to Int in Java. Do upvote our blog to help other ninjas grow.

Head over to our practice platform Code360 to practice top problems, attempt mock tests, read interview experiences, and much more.!

Happy Reading!

Live masterclass