Error: NullPointerException

In Java, NullPointerException is a RuntimeException. NullPointerException is thrown when a program attempts to use an object/variable reference that has the null value assigned to it.

Null Pointer Exception can be thrown through one of the following reasons:

  • When a method is invoked, from a null object.
  • Accessing or modifying an object field that is null
  • Taking the length of null, as if it were an array
  • When you try to synchronize over a null object.

Consider the following example:
A Null Pointer Exception is being raised here:

import java.io.*; 

class abc
{ 
	public static void main (String[] args) 
	{ 
		
		String ptr = null; 

		// Checking if ptr is null using try catch. 
		try
		{ 
			if (ptr.equals("randomString")) 
				System.out.print("Same"); 
			else
				System.out.print("Not Same");			 
		} 
		catch(NullPointerException e) 
		{ 
			System.out.print("Caught NullPointerException"); 
		} 
	} 
} 

The output fo the Above example is Caught NullPointerException

In the above case, a Null Pointer Exception is being caused because of calling equals on a literal rather than on the object.

This issue can be solved by reversing the operands in the .equals() function.

Refer to the following example for solving the Null Pointer Exception:

 import java.io.*; 

    class abc
    { 
    	public static void main (String[] args) 
    	{ 
    		
    		String ptr = null; 

    		// Checking if ptr is null using try catch. 
    		try
    		{ 
    			if ("randomString".equals(ptr)) 
    				System.out.print("Same"); 
    			else
    				System.out.print("Not Same");			 
    		} 
    		catch(NullPointerException e) 
    		{ 
    			System.out.print("Caught NullPointerException"); 
    		} 
    	} 
    } 

The output for this example would be Not Same

You can also refer to the following to Understand more about Null Pointer Exception.