Null Pointer Exception In Java
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
import java.util.UUID;
import java.io.*;
class Singleton
{
private static Singleton single = null ;
private String ID = null ;
private Singleton()
{
ID = UUID.randomUUID().toString();
}
public static Singleton getInstance()
{
if (single == null )
single = new Singleton();
return single;
}
public String getID()
{
return this .ID;
}
}
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
import java.io.*;
class GFG
{
public static void main (String[] args)
{
String ptr = null ;
try
{
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
import java.io.*;
class GFG
{
public static void main (String[] args)
{
String ptr = null ;
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
import java.io.*;
class GFG {
public static void main(String[] args)
{
String s = "" ;
try {
System.out.println(getLength(s));
}
catch (IllegalArgumentException e) {
System.out.println(
"IllegalArgumentException caught" );
}
s = "GeeksforGeeks" ;
try {
System.out.println(getLength(s));
}
catch (IllegalArgumentException e) {
System.out.println(
"IllegalArgumentException caught" );
}
s = null ;
try {
System.out.println(getLength(s));
}
catch (IllegalArgumentException e) {
System.out.println(
"IllegalArgumentException caught" );
}
}
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
import java.io.*;
class GFG {
public static void main(String[] args)
{
String str = null ;
String message
= (str == null ) ? "" : str.substring( 0 , 5 );
System.out.println(message);
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
- Otherwise, if str point to actual data, the message will retrieve the first 6 characters of it as in case
- 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:
- String comparison with literals
- Keeping a Check on the arguments of a method
- 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.
Last Updated :
19 Feb, 2024
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...