The Wayback Machine - https://web.archive.org/web/20241115183439/https://www.geeksforgeeks.org/null-pointer-exception-in-java/
Open In App

Null Pointer Exception In Java

Last Updated : 19 Feb, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

NullPointerException is a RuntimeException. In Java, a special null value can be assigned to an object reference. NullPointerException is thrown when a program attempts to use an object reference that has the null value.

Reason for Null Pointer Exception

These are certain reasons for Null Pointer Exception as mentioned below: 

  • Invoking a method from a null object.
  • Accessing or modifying a null object’s field.
  • Taking the length of null, as if it were an array.
  • Accessing or modifying the slots of null objects, as if it were an array.
  • Throwing null, as if it were a Throwable value.
  • When you try to synchronize over a null object.

Why do we need the Null Value? 

Null is a special value used in Java. It is mainly used to indicate that no value is assigned to a reference variable. One application of null is in implementing data structures like linked lists and trees. Other applications include the Null Object pattern (See this for details) and the Singleton pattern. The Singleton pattern ensures that only one instance of a class is created and also, aims for providing a global point of access to the object.

A simple way to create at most one instance of a class is to declare all its constructors as private and then, create a public method that returns the unique instance of the class:

Java




// To use randomUUID function.
import java.util.UUID;
import java.io.*;
  
class Singleton
{
    // Initializing values of single and ID to null.
    private static Singleton single = null;
    private String ID = null;
  
    private Singleton()
    {
        /* Make it private, in order to prevent the 
           creation of new instances of the Singleton
           class. */
  
        // Create a random ID
        ID = UUID.randomUUID().toString();
    }
  
    public static Singleton getInstance()
    {
        if (single == null)
            single = new Singleton();
        return single;
    }
  
    public String getID()
    {
        return this.ID;
    }
}
  
// Driver Code
public class TestSingleton
{
    public static void main(String[] args)
    {
        Singleton s = Singleton.getInstance();
        System.out.println(s.getID());
    }
}


Output: 

10099197-8c2d-4638-9371-e88c820a9af2

In above example, a static instance of the singleton class. That instance is initialized at most once inside the Singleton getInstance method.

How to Avoid the NullPointerException? 

To avoid the NullPointerException, we must ensure that all the objects are initialized properly, before you use them. When we declare a reference variable, we must verify that object is not null, before we request a method or a field from the objects.
Following are the common problems with the solution to overcome that problem.

Case 1 : String comparison with literals

A very common case problem involves the comparison between a String variable and a literal. The literal may be a String or an element of an Enum. Instead of invoking the method from the null object, consider invoking it from the literal. 

Below is the Example of the Case 1:

Java




// A Java program to demonstrate that invoking a method
// on null causes NullPointerException
import java.io.*;
  
class GFG
{
    public static void main (String[] args)
    {
        // Initializing String variable with null value
        String ptr = null;
  
        // Checking if ptr.equals null or works fine.
        try
        {
            // This line of code throws NullPointerException
            // because ptr is null
            if (ptr.equals("gfg"))
                System.out.print("Same");
            else 
                System.out.print("Not Same");
        }
        catch(NullPointerException e)
        {
            System.out.print("NullPointerException Caught");
        }
    }
}


Output: 

NullPointerException Caught

We can avoid NullPointerException by calling equals on literal rather than object.

Java




// A Java program to demonstrate that we can avoid
// NullPointerException
import java.io.*;
  
class GFG
{
    public static void main (String[] args)
    {
        // Initializing String variable with null value
        String ptr = null;
  
        // Checking if ptr is null using try catch.
        try
        {
            if ("gfg".equals(ptr))
                System.out.print("Same");
            else 
                System.out.print("Not Same");            
        }
        catch(NullPointerException e)
        {
            System.out.print("Caught NullPointerException");
        }
    }
}


Output: 

Not Same
 

Case 2 : Keeping a Check on the arguments of a method

Before executing the body of your new method, we should first check its arguments for null values and continue with execution of the method, only when the arguments are properly checked. Otherwise, it will throw an IllegalArgumentException and notify the calling method that something is wrong with the passed arguments. 

Below is the Example of the Case 2:

Java




// A Java program to demonstrate that we should
// Check if parameters are null or not before
// Using them.
import java.io.*;
  
class GFG {
    public static void main(String[] args)
    {
        // String s set an empty string  and calling
        // getLength()
        String s = "";
        
        try {
            System.out.println(getLength(s));
        }
        catch (IllegalArgumentException e) {
            System.out.println(
                "IllegalArgumentException caught");
        }
  
        // String s set to a value and calling getLength()
        s = "GeeksforGeeks";
        
        try {
            System.out.println(getLength(s));
        }
        catch (IllegalArgumentException e) {
            System.out.println(
                "IllegalArgumentException caught");
        }
  
        // Setting s as null and calling getLength()
        s = null;
        
        try {
            System.out.println(getLength(s));
        }
        catch (IllegalArgumentException e) {
            System.out.println(
                "IllegalArgumentException caught");
        }
    }
  
    // Function to return length of string s. It throws
    // IllegalArgumentException if s is null.
    public static int getLength(String s)
    {
        if (s == null)
            throw new IllegalArgumentException(
                "The argument cannot be null");
        
        return s.length();
    }
}


Output: 

0
13
IllegalArgumentException caught

Case 3 : Use of Ternary Operator

The ternary operator can be used to avoid NullPointerException. First, the Boolean expression is evaluated. If the expression is true then, the value1 is returned, otherwise, the value2 is returned. We can use the ternary operator for handling null pointers:

Java




// A Java program to demonstrate that we can use
// Ternary operator to avoid NullPointerException.
import java.io.*;
  
class GFG {
    public static void main(String[] args)
    {
        // Initializing String variable with null value
        String str = null;
        String message
            = (str == null) ? "" : str.substring(0, 5);
  
        System.out.println(message);
  
        // Initializing String variable with null value
        str = "Geeksforgeeks";
        message = (str == null) ? "" : str.substring(0, 5);
        System.out.println(message);
    }
}


Output: 

Geeks

The message variable will be empty if str’s reference is null as in case

  1. Otherwise, if str point to actual data, the message will retrieve the first 6 characters of it as in case
  2. Related Article – Interesting facts about Null in Java 

Frequently Asked Questions

1. What is NullPointerException in Java?

NullPointerException in Java is a type RuntimeException.

2. Why Null Pointer Exception Occurs?

NullPointerException occurs when one tries to access or manipulate object reference that has a Null value stored in it.

3. How to handle a Null Pointer Exception in Java?

There are certain methods to handle Null Pointer Exception in Java are mentioned below:

  1. String comparison with literals
  2. Keeping a Check on the arguments of a method
  3. Use of Ternary Operator

4. Reason for Null Pointer Exception.

NullPointerException is thrown when a program attempts to use an object reference that has the null value.



Previous Article
Next Article

Similar Reads

Comparison of Exception Handling in C++ and Java
Both languages use to try, catch and throw keywords for exception handling, and their meaning is also the same in both languages. Following are the differences between Java and C++ exception handling: Java C++ Only throwable objects can be thrown as exceptions.All types can be thrown as exceptions.We can catch Exception objects to catch all kinds o
4 min read
Java | Exception Handling | Question 1
Predict the output of following Java program class Main { public static void main(String args[]) { try { throw 10; } catch(int e) { System.out.println("Got the Exception " + e); } } } (A) Got the Exception 10 (B) Got the Exception 0 (C) Compiler Error Answer: (C) Explanation: In Java only throwable objects (Throwable objects are instances
1 min read
Java | Exception Handling | Question 2
class Test extends Exception { } class Main { public static void main(String args[]) { try { throw new Test(); } catch(Test t) { System.out.println("Got the Test Exception"); } finally { System.out.println("Inside finally block "); } } } (A) Got the Test Exception Inside finally block (B) Got the Test Exception (C) Inside finall
1 min read
Java | Exception Handling | Question 3
Output of following Java program? class Main { public static void main(String args[]) { int x = 0; int y = 10; int z = y/x; } } (A) Compiler Error (B) Compiles and runs fine (C) Compiles fine but throws ArithmeticException exception Answer: (C) Explanation: ArithmeticException is an unchecked exception, i.e., not checked by the compiler. So the pro
1 min read
Java | Exception Handling | Question 4
class Base extends Exception {} class Derived extends Base {} public class Main { public static void main(String args[]) { // some other stuff try { // Some monitored code throw new Derived(); } catch(Base b) { System.out.println("Caught base class exception"); } catch(Derived d) { System.out.println("Caught derived class exception
1 min read
Java | Exception Handling | Question 8
class Test { public static void main (String[] args) { try { int a = 0; System.out.println ("a = " + a); int b = 20 / a; System.out.println ("b = " + b); } catch(ArithmeticException e) { System.out.println ("Divide by zero error"); } finally { System.out.println ("inside the finally block"); } } } (A) Compile
1 min read
Java | Exception Handling | Question 6
class Test { public static void main(String[] args) { try { int a[]= {1, 2, 3, 4}; for (int i = 1; i <= 4; i++) { System.out.println ("a[" + i + "]=" + a[i] + "\n"); } } catch (Exception e) { System.out.println ("error = " + e); } catch (ArrayIndexOutOfBoundsException e) { System.out.println ("ArrayIn
1 min read
Java | Exception Handling | Question 7
Predict the output of the following program. class Test { String str = "a"; void A() { try { str +="b"; B(); } catch (Exception e) { str += "c"; } } void B() throws Exception { try { str += "d"; C(); } catch(Exception e) { throw new Exception(); } finally { str += "e"; } str += "f"; } void
1 min read
Java | Exception Handling | Question 8
Predict the output of the following program. class Test { int count = 0; void A() throws Exception { try { count++; try { count++; try { count++; throw new Exception(); } catch(Exception ex) { count++; throw new Exception(); } } catch(Exception ex) { count++; } } catch(Exception ex) { count++; } } void display() { System.out.println(count); } publi
1 min read
Exception Propagation in Java
Prerequisite : Exceptions in Java, Checked vs Unchecked Exceptions Exception propagation : An exception is first thrown from the top of the stack and if it is not caught, it drops down the call stack to the previous method. After a method throws an exception, the runtime system attempts to find something to handle it. The set of possible "something
3 min read
Exception Handling with Method Overriding in Java
An Exception is an unwanted or unexpected event, which occurs during the execution of a program i.e at run-time, that disrupts the normal flow of the program’s instructions. Exception handling is used to handle runtime errors. It helps to maintain the normal flow of the program. In any object-oriented programming language, Overriding is a feature t
6 min read
Java - Exception Handling With Constructors in Inheritance
Java provides a mechanism to handle exceptions. To learn about exception handling, you can refer to exceptions in java. In this article, we discuss exception handling with constructors when inheritance is involved. In Java, if the constructor of the parent class throws any checked exception, then the child class constructor can throw the same excep
7 min read
User-defined Custom Exception in Java
An exception is an issue (run time error) that occurred during the execution of a program. When an exception occurred the program gets terminated abruptly and, the code past the line that generated the exception never gets executed. Java provides us the facility to create our own exceptions which are basically derived classes of Exception. Creating
3 min read
Infinity or Exception in Java when divide by 0?
Consider the following code snippets: public class Geeksforgeeks { public static void main(String[] args) { double p = 1; System.out.println(p/0); } } Output: Infinity public class Geeksforgeeks { public static void main(String[] args) { int p = 1; System.out.println(p/0); } } Output: Exception in thread "main" java.lang.ArithmeticException: / by z
1 min read
Array Index Out Of Bounds Exception in Java
Java supports the creation and manipulation of arrays as a data structure. The index of an array is an integer value that has value in the interval [0, n-1], where n is the size of the array. If a request for a negative or an index greater than or equal to the size of the array is made, then the JAVA throws an ArrayIndexOutOfBounds Exception. This
4 min read
Types of Exception in Java with Examples
Java defines several types of exceptions that relate to its various class libraries. Java also allows users to define their own exceptions. Built-in Exceptions: Built-in exceptions are the exceptions that are available in Java libraries. These exceptions are suitable to explain certain error situations. Below is the list of important built-in excep
8 min read
Different Ways to Print Exception Messages in Java
In Java, there are three methods to print exception information. All of them are present in the Throwable class. Since Throwable is the base class for all exceptions and errors, we can use these three methods on any exception object. Methods to Print Exceptions in Java There are three methods to print exception messages in Java. These are: 1. java.
2 min read
Output of Java program | Set 12(Exception Handling)
Prerequisites : Exception handling , control flow in try-catch-finally 1) What is the output of the following program? public class Test { public static void main(String[] args) { try { System.out.printf("1"); int sum = 9 / 0; System.out.printf("2"); } catch(ArithmeticException e) { System.out.printf("3"); } catch(Exce
3 min read
Understanding OutOfMemoryError Exception in Java
In Java, all objects are stored in a heap. They are allocated using a new operator. The OutOfMemoryError Exception in Java looks like this: Exception in thread "main" java.lang.OutOfMemoryError: Java heap space Usually, this error is thrown when the Java Virtual Machine cannot allocate an object because it is out of memory. No more memory could be
9 min read
Nested try blocks in Exception Handling in Java
In Java , we can use a try block within a try block. Each time a try statement is entered, the context of that exception is pushed onto a stack. Given below is an example of a nested try. In this example, the inner try block (or try-block2) is used to handle ArithmeticException, i.e., division by zero. After that, the outer try block (or try-block)
3 min read
Replace null values with default value in Java Map
Given a Map with null values in it, the task is to replace all the null values with a default value. Examples: Input: map = {1=1, 2=2, 3=null, 4=4, 5=null, 6=null}, defaultValue = 0 Output: {1=1, 2=2, 3=0, 4=4, 5=0, 6=0} Input: map = {1=A, 2=B, 3=null, 4=D, 5=null, 6=null}, defaultValue = 'Z' Output: {1=A, 2=B, 3=Z, 4=D, 5=Z, 6=Z} Approach: Get the
3 min read
Program to check if the String is Null in Java
Given a string str, the task is to check if this string is null or not, in Java. Examples: Input: str = null Output: True Input: str = "GFG" Output: False Approach: Get the String to be checked in str We can simply compare the string with Null using == relational operator. Syntax: if(str == null) Print true if the above condition is true. Else prin
1 min read
Why NULL is Not Allowed in Java TreeSet?
TreeSet is one of the most important implementations of the SortedSet interface in Java that uses a Tree for storage. The ordering of the elements is maintained by a set using their natural ordering whether or not an explicit comparator is provided. This must be consistent with equals if it is to correctly implement the Set interface. Example: Java
2 min read
Method overloading and null error in Java
In Java it is very common to overload methods. Below is an interesting Java program. Java Code public class Test { // Overloaded methods public void fun(Integer i) { System.out.println(&quot;fun(Integer ) &quot;); } public void fun(String name) { System.out.println(&quot;fun(String ) &quot;); } // Driver code public static void main
2 min read
Calling a method using null in Java
Prerequisite: null in Java, Static in Java Can you predict the output of the following program?? Before answering, please observe the fact that in given code, fun() is a static member that belongs to the class and not to any instance. // Java program to illustrate calling // static method using Null public class GFG { public static void fun() { Sys
2 min read
Interesting facts about null in Java
Almost all the programming languages are bonded with null. There is hardly a programmer, who is not troubled by null. In Java, null is associated java.lang.NullPointerException. As it is a class in java.lang package, it is called when we try to perform some operations with or without null, and sometimes we don't even know where it has happened. Bel
7 min read
C++ | Exception Handling | Question 1
#include <iostream> using namespace std; int main() { int x = -1; try { cout << "Inside try \n"; if (x < 0) { throw x; cout << "After throw \n"; } } catch (int x ) { cout << "Exception Caught \n"; } cout << "After catch \n"; return 0; } (A) Inside try Exception Caught After th
1 min read
C++ | Exception Handling | Question 2
What is the advantage of exception handling ? Remove error-handling code from the software's main line of code. A method writer can choose to handle certain exceptions and delegate others to the caller. An exception that occurs in a function can be handled anywhere in the function call stack. (A) Only 1 (B) 1, 2 and 3 (C) 1 and 3 (D) 1 and 2 Answer
1 min read
C++ | Exception Handling | Question 3
What should be put in a try block? 1. Statements that might cause exceptions 2. Statements that should be skipped in case of an exception (A) Only 1 (B) Only 2 (C) Both 1 and 2 Answer: (C)Explanation: The statements which may cause problems are put in try block. Also, the statements which should not be executed after a problem occurred, are put in
1 min read
C++ | Exception Handling | Question 4
Output of following program #include<iostream> using namespace std; class Base {}; class Derived: public Base {}; int main() { Derived d; try { throw d; } catch(Base b) { cout<<"Caught Base Exception"; } catch(Derived d) { cout<<"Caught Derived Exception"; } return 0; } (A) Caught Derived Exception (B) Caught B
1 min read
three90RightbarBannerImg