---
title: Null Pointer Exception in Java - Scaler Topics
description: This article by Scaler Topics will provide you with an understanding of the null pointer exception in Java; read to know more.
author: Atharva Mahamuni
category: Java
---
:::section{.main}
The null pointer exception in java is a **runtime exception**, which is thrown when the program tries to use an object reference that is set to the `null` value. Refer to the following coding example to understand the null pointer exception in java.
**Example :**
```java
class Main {
public static void main(String[] args) {
// Setting null value to the obj object
Object obj = null;
// Using an object with a null value
System.out.println(obj.toString()); // It throws NullPointerException
}
}
```
**Output :**
```plaintext
Exception in thread "main" java.lang.NullPointerException
at Main.main(Main.java:8)
```
In this, we initialized the null value to an object, `obj`. On the `obj` object, we performed the `toString()` operation. Because the value of obj is null, it throws the null pointer exception, as shown in the output.
Let's try to understand the hierarchy of null pointer exceptions in java :

As we discussed, the null pointer exception in Java is a runtime exception, which is why it extends from the runtime exception class. The runtime exception class inherits the exception class. Throwable is a subclass of the object class, and the exception class is derived from the throwable class.
:::
:::section{.main}
## Reason for Null Pointer Exception
There are multiple scenarios where the null pointer exception occurs.
### The Method is Invoked Using a Null Object
When we try to invoke the method with the null object, it gives the null pointer exception, as shown in the following code.
```java
class FunClass {
// Method which returns the null object
public static FunClass funMethod() {
return null;
}
public void print(String s) {
System.out.println(s.toLowerCase());
}
}
class Main {
public static void main(String[] args) {
// Creating the object of FunClass
FunClass obj = FunClass.funMethod();
// Calling the print method of FunClass with null object
obj.print("Hello, World!");
}
}
```
**Output :**
```plaintext
Exception in thread "main" java.lang.NullPointerException
at Main.main(Main.java:18)
```
In the above program, there are `2` methods in the funClass; one of the methods is `funMethod`, which returns the null value for object obj on line 15. When we use this null object on line 18 to print the string, it gives the null pointer exception as we can't use the null object for method invocation.
### Access Field of Null Object
Consider the following program where the null object is used to access the number field. It can raise the null pointer exception.
```java
class FunClass {
// Number field
int funNumber = 100;
// funMethod which returns the null object
public static FunClass funMethod() {
return null;
}
}
class Main {
public static void main(String[] args) {
// Creating the object of FunClass and assigning it to null
FunClass obj = FunClass.funMethod();
// Accessing the funNumber field with a null object
// It gives the null pointer exception
int num = obj.funNumber;
}
}
```
**Output :**
```plaintext
Exception in thread "main" java.lang.NullPointerException
at Main.main(Main.java:18)
```
In the above program, there is a number field of type integer with variable name `funNumber`. When we use the null object on line 18 to access this number, it gives the null pointer exception as we can't use the null object to access the fields.
### Passing Null Object as an Argument
In the following program, we passed the null value as an argument to the function. Due to the null object invoking method, a null pointer exception occurs.
```java
public class Main {
// method to print the string in all upper-case
public static void print_upper_case(String s) {
System.out.println(s.toUpperCase());
}
public static void main(String[] args) {
// call the method by passing a null object as an argument
print_upper_case(null);
}
}
```
**Output :**
```plaintext
Exception in thread "main" java.lang.NullPointerException
at Main.print_upper_case(Main.java:4)
at Main.main(Main.java:9)
```
The above program passes the null value to the function call at line number `9`. But we can't perform the operations on the null string. That's why the null object invoking method null pointer exception occurs.
### Getting Length of a Null Array
If we perform the in-built operations on the null array, it throws a null pointer exception, as in the following code.
```java
public class Main {
public static void main(String[] args) {
// creating an array and assigning it to the null value
int[] funArray = null;
//Finding the length of the null array gives the null pointer exception
System.out.println("Array Length:" + funArray.length);
}
}
```
**Output :**
```plaintext
Exception in thread "main" java.lang.NullPointerException
at Main.main(Main.java:8)
```
In the above code, on line 5, we declared the array funArray and assigned it a null value. When we tried to use the length method on line 8, it gave the null pointer exception.
### Access Index of a Null Array
If the array is null, and if we try to access the element by the index number of an array, then it gives the null pointer exception.
```java
public class Main {
public static void main(String[] args) {
// Declaring array and assigning it to the null value
int[] myArray = null;
// Accessing the index of the null array gives the null pointer exception
System.out.println("Value at index 3 of myArray is " + myArray[3]);
}
}
```
**Output :**
```plaintext
Exception in thread "main" java.lang.NullPointerException
at Main.main(Main.java:7)
```
In the above code, we declare the array myArray on line 4 and assign it a null value. When we try to access the index of this null array on line 7, we get the null pointer exception.
### Synchronization on a Null Object
We can't use the null value in a synchronized block; otherwise, it throws the null pointer exception, as demonstrated in the following program.
```java
public class Main {
// Assigning the null value to the mutexVar
public static String mutexVar = null;
public static void main(String[] args) {
// null value throws the null pointer exception in synchronised block
synchronized (mutexVar) {
System.out.println("Synchronized block");
}
}
}
```
**Output :**
```plaintext
Exception in thread "main" java.lang.NullPointerException
at Main.main(Main.java:7)
```
In the above program, we declared the variable mutexVar and assigned it a null value. On line 7, we used the null value in the synchronized block, which gave the null pointer exception.
### By Throwing Null
If the program throws the null value directly, it can give the null pointer exception as demonstrated in the following program.
```java
public class Main {
public static void main(String[] args) {
// Throwing null gives a null pointer exception
throw null;
}
}
```
**Output :**
```plaintext
Exception in thread "main" java.lang.NullPointerException
at Main.main(Main.java:4)
```
:::
:::section{.main}
## Requirement of NULL Value
The null value represents the no value assigned to the reference variable. There are multiple uses of null values while designing linked lists, trees, or singleton design patterns. Thus, `null` values are very useful in Java in various places.
Its utility extends across various applications, including linked list and tree data structure implementation. Additionally, it finds application in design patterns like the Null Object pattern, which substitutes null references with objects that perform no action or provide default behaviour and the Singleton pattern.
```java
public class Example {
public static void main(String[] args) {
String name = null;
// NullPointerException without handling null value (alternative)
// This line will throw NullPointerException if name is null
System.out.println("Length of name: " + name.length());
}
}
```
**Output:**
```
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.length()" because "<local1>" is null
at Example.main(Example.java:6)
```
**Explanation:**
In the above example, the string name is made null and then we are trying to find the length of it, which causes the null pointer exception by which the code fails to run successfully. We can avoid it using the try-catch block statements.
:::
:::section{.main}
## Avoiding the NullPointerException
### String Comparison with Literals
It is a common problem that the null pointer exception occurs when we invoke the `equals` method with the null object, as shown below.
```java
class Main {
public static void main(String[] args) {
// Assigning myString to the null value
String myString = null;
try {
// This line throws null pointer exception as we are comparing with null value
if (myString.equals("hello"))
System.out.print("Same");
else
System.out.print("Not Same");
} catch (NullPointerException e) {
System.out.print("NullPointerException Caught");
}
}
}
```
**Output :**
```plaintext
NullPointerException Caught
```
We can avoid the null pointer exception in the above code by invoking the equals method with a literal instead of the `myString` variable on line 8.
```java
class Main {
public static void main(String[] args) {
// Assigning myString to the null value
String myString = null;
try {
// This line throws null pointer exception as we are comparing with null value
if ("hello".equals(myString))
System.out.print("Same");
else
System.out.print("Not Same");
} catch (NullPointerException e) {
System.out.print("NullPointerException Caught");
}
}
}
```
**Output :**
```plaintext
Not Same
```
### Keeping a Check on the Arguments of a Method
We can avoid the null pointer exception in Java by checking whether the arguments are null. We can write a simple if condition, as shown in the following program.
```java
class Main {
// Function to get the length of the string
public static int getLength(String s) {
// checking if the string is null
if (s == null)
throw new IllegalArgumentException("The argument cannot be null");
//If the string is not null, return the length of the string
return s.length();
}
public static void main(String[] args) {
// Assigning the null value to the myString variable
String myString = null;
try {
System.out.println(getLength(myString));
} catch (IllegalArgumentException e) {
System.out.println("IllegalArgumentException caught");
}
}
}
```
**Output :**
```plaintext
IllegalArgumentException caught
```
### Use of a Ternary Operator
It is also possible to use the ternary operator to check the condition of whether the given argument is null or not. We can check it as shown on line number `6` and line number `11` in the following program.
```java
class Main {
public static void main(String[] args) {
// Assigning the null value to myString
String myString = null;
// handling null pointer exception with the ternary operator
String message = (myString == null) ? "Can not perform uppercase because of null value" : myString.toUpperCase();
System.out.println(message);
// Assigning the hello to the string variable
myString = "hello";
message = (myString == null) ? "Can not perform uppercase because of null value" : myString.toUpperCase();
System.out.println(message);
}
}
```
**Output :**
```plaintext
Can not perform uppercase because of null value
HELLO
```
:::
:::section{.summary}
## Conclusion
- Null pointer exception in java is a **runtime exception**.
- Null pointer exception occurs when the program uses the reference of the object set to `null`.
- We can handle null pointer exceptions by making some changes in programs, such as invoking methods directly with literals instead of null objects.
- We can use the conditional checks to avoid the invalid object invocation.
:::
:::section{.faq-section}
## FAQs
Q: **How do you pass a NullPointerException in Java?**
A: We handle it using try-catch blocks or by adding null checks.
Q: **Should we catch NullPointerException in Java?**
A: Yes, it's generally advisable to catch and handle NullPointerException in Java to prevent unexpected program termination.
Q: **What is NullPointerException caused by?**
A: NullPointerException is typically caused by attempting to access or modify an object reference that is null.
:::