Java Null Pointer Exception 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.
For instance, it can be situations like.

Reasons for null pointer exception in java-

  • 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 the null object, as if it were an array.
  • Throwing null, as if it were a Throwable value.
  • When you try to synchronize over a null object.

Here’s the class hierarchy of java exceptions.

null pointer exception java

When we get null pointer exceptions in java?

Basically, wherever we use the value null and if we mishandle it, there are chances of NullPointerException to be thrown. The Java null value has wide implementation from data structures to the singleton class and many more. In other words, if we have to initialize an object and we don’t know its value, java assigns a null value to it by default.

Here’s a demo program to demonstrate use charAt method to return a character in String at a particular index and, how it returns null if the string is not initialized.

public class Null { public static void main(String[] args) 
{ 
String s1 = "nullPointerException"; 
String s2 = null; 
System.out.println(s1.charAt(0)); 
System.out.println(s2.charAt(0)); 
} 
}

OUTPUT

n
Exception in thread "main" java.lang.NullPointerException
	at WordPress.Null.main(Null.java:8)

See how s2 is initialized with the value null, to intentionally throw the null pointer exception.
Note that if we don’t initialize the value at all then a compilation error will be shown saying variable not initialized.

public class Null {
public static void main(String[] args) {
String s1 = "nullPointerException";
String s2 = null;
System.out.println(s1.charAt(0));if(s2 == null)
		    System.out.println("Variable not initialized!");
		else
		    System.out.println(s2.charAt(0));
	}
}

OUTPUT

n
Variable not initialized!

But what if we are working with many objects?

As you can see that we didn’t check the validity for s1! In a real-world scenario, it will be impossible to individually check all the objects used in a program before accessing it! To simplify this we can use try-catch!

public class Null {
	public static void main(String[] args) {
		try {
		String s1 = "nullPointerException";
		String s2 = null;
		System.out.println(s1.charAt(0));
		System.out.println(s2.charAt(0));
		}
		catch(Exception e) {
			System.out.println("Variable not initialized!");
		}
	}
}

OUTPUT

n
Variable not initialized!

Finally, if any Exception is thrown in the try block them the catch block will get executed. Hence, resolving our problem (how to handle null pointer exception in java).