×

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.


Related Topics

Compare Two Times in Java

Definition The compareTo() function of the LocalTime class is used to compare times. The class's compareTo() method compares two LocalTime objects. Here we have two objects that have to be compared: the...

4 minutes read.

Traverse through HashMap in Java

In this tutorial, we will discuss traversing through HashMap in Java Introduction: HashMap<Key, Value> is a part of the java collection implemented from the java 1.2 version. HashMap is written as HashMap<K,...

4 minutes read.

Awesome explanation of Strings in Java

What do you mean by String? Strings are a collection of characters that are commonly used in Java programming. Strings are regarded as objects in the Java programming language. “String” is a...

4 minutes read.

Menu Driven Program in Java

Menu Driven Program in Java The menu-driven program in Java is a program that displays a menu and then takes input from the user to choose an option from the displayed...

3 minutes read.

How to take String Input in Java

There are various ways to take String input in Java. In this section, we are going to discuss how to take String input in Java. There are following ways to...

5 minutes read.

Java Integer compare() method

The compare() method of Integer class compares the two specified int values. Syntax public static int compare(int x, int y) Parameters The parameters ‘x’ and ‘y’ represent the first and second int values to...

2 minutes read.

Singleton class in Java

What is Singleton class in Java? Singleton means it is one. That means we can create only one instance or object of a class. For example, let us have a class...

3 minutes read.

Contextual keywords in Java

Contextual keywords were earlier known as restricted identifiers and restricted keywords. Context keywords are chosen based on their expected placement in the syntactic grammar. These are the keywords in the code...

3 minutes read.

Java Custom Exception

Java Custom Exception Java language facilitates us to create our own exceptions. The class intended to throw the Custom Exception has to be derived from the Java Exceptionor RuntimeExceptionclass. The Java...

4 minutes read.

How to override toString() method in Java?

Java is an object-oriented language. It only works with classes and objects. Thus, whenever we need to calculate, we need an object or objects that belong to the class. The Java method...

2 minutes read.

Creating API Document Javadoc tool

The JavaDoc utility is a document generator tool written in Java that generates standard documentation in HTML format. It parses declarations and documentation in a source file collection that describes...

3 minutes read.

Java Thread Dump Analyzer

Thread: A thread is a PC program that is stacked into the PC's memory and is under execution. It tends to be executed by a processor or a bunch of processors....

15 minutes read.

Java Program to Print Permutations of String

A string is given and you need to print all the possible ways for that string. Permutation is arranging the characters of a string to get outputs from the given...

3 minutes read.

Java Swing Time Picker

Prerequisites In this tutorial, we will learn the time picker in java swing. Before learn time picker, we should learn about java swing. Java Swing Introduction The Java Foundation Classes include Java Swing....

5 minutes read.

How to check valid date in Java?

Every time we get data for any application, we must first ensure that it is accurate before continuing with any further processing. We might have to confirm the following while dealing...

4 minutes read.

Java Instanceof Keyword

To determine whether an object is an instance of the supplied type in Java, use the instanceof operator (class or subclass or interface). The type of comparison in java differentiates the...

4 minutes read.

How to Convert Date to String in Java

How to Convert Date to String in Java We need to convert Date to String in Java may for displaying purpose. We can convert Date to String in Java using the format() method of java.text.DateFormat class. There...

2 minutes read.

Advantages and Disadvantages of Strings in Java

What is a String? Java is an object-oriented, platform-independent, high-level, general-purpose, and interpreted programming language.Sun Microsystems is known as the founder of java in 1991; the Java programming language was developed...

4 minutes read.

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...

3 minutes read.

HashMap Vs HashTable

HashMap HashMap is the basic implementation of the map interface in Java. HashMap stores the data in key and value pairs. Keys are used to access the value of the element. It...

5 minutes read.