Null Pointer Exception in Java
It is a runtime error exception. The null value is allocated to the object reference in this exception. We will explicitly throw this null pointer exception when the program wants to implement an object reference value consisting of a null value. That means instead of using an object reference value, the code takes a null reference value.
What is a Null Object?
A null object is nothing but an object that is created without any implementation. That object is called a null object. Using all these null objects leads to null pointer exceptions. A null value can be used in many ways in Java. It is the special value, and it is stated as the object reference variable is not assigned by any value.
Example Java program for implementing null pointer exception along with throwing a user defined exception.
Code
import java.io.*;
import java.lang.*;
class Exception
{
static int a=81, b=0, c;
static int div()
{
try
{
if(b==0) // throws an exception
{
//throws an exception explicitly
throw new Arithmetic Exception(" Division by zero error ");
} // if
else
{
return(a/b);
} // else
} // try
catch(Arithmetic Exception ae)
{
System.out.print("Arithmetic Exception caught at div()");
throw ae; // rethrows an exception
} //catch
} //div
public static void main(String args[]) throws IO Exception
{
try
{
int x=div();
System.out.print(" x = "+ x);
try
{
String str = null;
System.out.print(str.length()); // Null Pointer Exception
} // inner try
catch(NullPointerException npe)
{
System.out.print("Null Pointer Exception at main() = " + npe);
} // catch
} // outer try
catch(ArithmeticException ae)
{
System.out.print(" Exception Recaught at main() = " + ae);
} // catch
finally
{
System.out.print(" Closing the Exception Handling demo program");
} // finally
} // main
} // Exception Handling
Output
Arithmetic Exception caught at div()
Exception Recaught at main() = java. lang. Arithmetic Exception: Division by zero error
Closing the Exception Handling demo program
A few cases where null pointer exceptions are thrown
- attempting to use the null object to invoke an instance and manipulate or access features by using the null object.
- to throw the empty string as a throwable value. Furthermore, whenever you attempt to synchronize over the null value.
- Invoking method with the help of a null object A special method is invoked on the null object. Then, in this case, a null pointer exception will be thrown.
- The Java programme changes the field value of a null object. In this case, the Java programme explicitly throws a null pointer exception.
- A null pointer exception occurs if we do not properly check the arguments present in the method. So, we pass null arguments to the respective method.
- Performing any operations on an empty array causes the application to throw a null pointer exception and the array cannot be read.
- When we try to control the access of multiple threads to a shared resource of a method or block, it is important to cross-check whether the synchronising value is null or not. Then we will synchronise over the null object.
How to avoid null pointer exceptions
To verify null pointer exceptions, we must check the initialization of reference variables before using any of them. And we also ensure that reference value should not be null.
Scenarios where null pointer exception is important
String Comparisons
Comparing the string with literal leads to null pointer exception. This is because the object of the string we are comparing is null. It is explained with an example code given below.
Code
class Demo
{
public static void main (String [] args)
{
String s1 = null;
if (s1. equals (" Hello"))
{
// print if objects are same
System. out. print("Same");
}
else
{
//print if objects are different
System. out. print (" not same ");
}
}
}
Output
Exception in java.lang.NullPointerException: Cannot invoke "String.equals(Object)" because "<local1>" is null at Demo.main(Demo.java:6)
The above program can be avoided by the null pointer exception in the below program
Code
class Demo
{
public static void main(String[] args)
{
String s2 = null;
if("HI”.equals(s2))
{
// print if objects are same
System.out.print("Same ");
}
else
{
System.out.print(" Not Same"); // print if objects are different
}
}
}
Output
Not Same
Other ways that include are by using ternary operator. In which we use Boolean expression and return 1 in case if the condition is true else, we will return 0 if the condition is false.