Null Pointer Exception in Java

Null Pointer Exception in Java

The NullPointerException is an unchecked exception in Java that occurs during runtime when we try to call a method or access a variable on a null reference. While working with Java, we might get a runtime error while running a Program. Java provides multiple methods by which we can fix these types of exceptions.

In this blog, we are going to learn NullPointerException, how it occurs, and how we can fix it in more detail.

Table of Contents:

What is a NullPointerException in Java?

A NullPointerException is a runtime error that occurs when the JVM(Java Virtual Machine) tries to access or modify an object or call a method on a null reference. Since null represents the absence of an object, calling methods, accessing fields, or performing operations on it leads to NullPointerException.

Why Does a NullPointerException Occur?

The NullPointerException can occur due to the following reasons:

  • When we are trying to call a method on an uninitialized object.
  • When we are trying to access the fields or invoking methods on a null object.
  • When we are trying to get the length of a null array.
  • When we are trying to pass null as a method argument without proper validation.

Need of Null Value

The null value in Java programming represents the absence of a value or an uninitialized reference. It is used in data structures like linked lists and trees to mark the last element.

It also helps in handling missing or optional data, such as database query results.

Additionally, null is useful for exception handling, indicating errors or failed operations.

Common Examples of NullPointerException

Here are the following examples of the NullPointerException in Java:

Example 1: NullPointerException When Calling an Instance Method

Suppose we have a string that contains a null value, and if we try to call a method on it, it will cause an exception.

Example:

Java

Output:

In the above example, we are trying to call the length() method on a null object, which results in a NullPointerException.

Example 2: NullPointerException While Accessing/Modifying the field of a null object

When we try to access or modify a field of a null object, a NullPointerException occurs. 

Example:

Java

Output:

Here, we are trying to modify a field of an uninitialized object.

Example 3: NullPointerException When null is Passed in the Method Argument

If null is passed as an argument, the length() method will throw a NullPointerException.

Example:

Java

Output:

Example 4: NullPointerException When null is thrown

When we are trying to throw a null value, Java will throw a NullPointerException.

Example:

Java

Output:

Example 5: NullPointerException When Getting the Length of a null Array

When we are trying to access the length of a null array, it may lead to a NullPointerException.

Example:

Java

Output:

How to Fix NullPointerException in Java

To avoid or fix a NullPointerException, it’s essential to validate objects before performing any operation on them. Let’s learn this concept in more detail:

1. Null Checks Before Calling Methods

You must check, whether an object is null or not before calling its methods to avoid such exceptions.

Example:

Java

Output:

By checking for null, we avoid calling methods on a null reference.

2. Handling Null Values Using Try-Catch Blocks

To handle null values efficiently, we can use try-catch block to catch the error.

Example:

Java

Output:

Since str is null, calling str.length() results in a NullPointerException because Java cannot access the length() method on a null reference. 

Note: We need to avoid catching NullPointerException unless it is very important. Instead, you need to always validate objects before accessing their properties or methods.

Look at the below example for a better understanding:

Java

Output:

3. Using Objects.requireNonNull()

The Objects.requireNonNull() method in Java is used to check if an object is null. If the object is null, it throws a NullPointerException

Example:

Java

Output:

The above code throws an exception with a meaningful message. 

4. Using Java’s Optional Class 

The Optional class, introduced in Java 8, provides a safer way to handle potentially null values and reduce the risk of these exceptions.

Example:

Java

Output:

  • We create an Optional<String> using Optional.ofNullable(null). Since we pass null, the Optional will be empty.
  • The orElse(“Guest”) method checks if a value is present:
    • If there is a value, it returns the actual value.
    • If there is no value (i.e., null), it returns the default “Guest”.

Best Practices for Avoiding NullPointerException

Let’s explore some approaches to avoid NullPointerException in Java Programs:

1. String Comparison with Literals

When comparing strings, it is recommended to use the literal string first to avoid NullPointerException.

Example:

Java

Output:

2. Handle Method Arguments and Returns

We must have to check the arguments and return values for null before using them.

Example:

Java

Output:

3. Use the Ternary Operator

We can use the ternary operator to assign a default value when a variable might be null. The ternary operator, also known as the conditional operator, returns one of two values based on a condition.

Example:

Java

Output:

Conclusion

So far in this article, We have learned how we can handle NullPointerException in Java Programs. The main reason for this exception is trying to access a variable or object that has not been initialized. We can avoid this exception by following best practices such as checking for null before accessing objects and using Objects.requireNonNull(), comparing strings with literals first, and using the ternary operator to assign default values. 

If you want to master all the concepts of Java language, you may refer to our Java course.

FAQs

1. What is NullPointerException in Java?

A NullPointerException occurs when the JVM tries to use a null reference as though it were an object, such as calling methods or accessing fields on it.

2. Why does a NullPointerException occur?

It occurs when an object is null, and an operation is performed on it (e.g., method invocation, accessing fields).

3. How to handle a NullPointerException in Java?

You can handle NullPointerException by using null checks, try-catch blocks, ternary operators, and methods like Objects.requireNonNull().

4. Can I catch NullPointerException?

Yes, you can catch a NullPointerException in Java using a try-catch block.

5. How to check if a list is empty or null in Java?

IsEmpty() method is used to check if a list is empty or not.

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.

Full Stack Developer Course Banner