×

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

Java Viva Questions and Answers

Question: Explain Java programming language. Answer: It is a high-level programming language. This programming language is based on the principles of object-oriented programming. Large-scale applications can be developed by using this...

16 minutes read.

Java Math nextAfter() Method

The nextAfter() method of Math class returns the floating-point value adjacent to the first argument in direction of the second argument. Syntax: public static double nextAfter (double start, double direction)public static float...

2 minutes read.

How to Convert char to int in Java

How to Convert char to int in Java When two variables of different types are involved in the single expression, Java compiler uses built-in library function to convert the variable to...

3 minutes read.

Java Short Keyword

Java supports eight different primitive datatypes. The language has predefined primitive datatypes that are given keyword names. Let's take a closer look at each of the eight primitive data types....

3 minutes read.

Enum Java Interview Questions

1. What exactly is Java? Java is a portable, high-level, object-oriented, robust, secure, platform-independent, multi-threaded, high-performance programming language. Developed in June 1991 by James Gosling, also known as Platform. 2. Enum is...

3 minutes read.

Fork Join in Java

Multithreaded processors are being introduced in new computer systems today. The operation is faster due to multicore CPUs. Therefore, it becomes essential for a programmer to leverage multithreaded processors effectively...

4 minutes read.

Thread Scheduler in java

Scheduling: it is defined as the execution of multiple threads on a single CPU in some order is called scheduling. Preemptive-priority scheduling: This algorithm schedules threads based on their priority relative to other...

11 minutes read.

How to Install Java on MAC

There are many possible ways to install java on mac. This article is based on the installation of java on mac. The operating system platform is Mac OS X, macOS and...

3 minutes read.

Creating a Custom Generic Class in Java

To indicate parameter types when creating generic classes, we utilize the <> symbol. The syntax used to generate objects of a generic class is as follows. // To create an instance...

4 minutes read.

Char and String differences in Java

Characters in Java Character (char) belongs to the characters group, which represents symbols in a character set, such as alphabets and numerals. A Java char has 16 bits in length and has a range...

5 minutes read.

Java RandomAccessfile

Writing and reading to random access files are done using this class. An array of many bytes is how a random access file operates. By changing the implied file pointer...

3 minutes read.

Java Integer toString() method

The toString() method of Java Integer class returns a String object which represents this Integer’s value. The second syntax returns a String object which represents the specified integer. The third syntax returns...

2 minutes read.

Java String getChars() Method

Java String getChars() method copies characters from current String to the destination character array . Syntax: public void getChars(int srcBeginIndex, int srcEndIndex, char[] destination, int dstBeginIndex) Parameters: srcBegin - index of the first character...

1 minute read.

Java Math multiplyFull() Method

The multiplyFull() method of Math class returns the exact product of the arguments. Syntax: public static long multiplyFull (int x, int y) Parameters: The parameters ‘x’ and ‘y’ represent the first value and second...

1 minute read.

Java Abstraction

Java Abstraction Abstraction is an advanced feature of Java to make it transparent. The main motive behind the abstraction is to deal with ideas, not with events. Abstraction is a process...

4 minutes read.

How to Convert String to boolean in Java

How to Convert String to boolean in Java There are two methods to convert String to boolean: Using parseBoolean(string) method Using valueOf(string) method If the string contains "True," "true," or "TRUE,"...

3 minutes read.

Java Full Stack

A person who can create both the front end and back end of an application is a full-stack developer. In essence, the term "Java full-stack" refers to a web developer...

9 minutes read.

Java Generics Questions

Introduction We'll walk through a few real-world examples of interview questions and responses for Java generics in this article. Java 5 saw the debut of the fundamental idea of generics. Due to...

9 minutes read.

Get yesterdays date by no of days in Java

In this tutorial, we are going to learn how to get yesterday’s date by the no of days in Java. Using the Calendar class, one can get the current date....

1 minute read.

Tribonacci series in Java

The Fibonacci series and the Tribonacci sequence are linked. The Fibonacci sequence, each element summates the three preceding terms, is expanded into the Tribonacci series in Java. Through specific examples,...

3 minutes read.