Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Reasons for NullPointerException
2.1.
Calling the instance method of a null object
2.1.1.
Code
2.2.
Java
2.2.1.
Output
2.3.
Modifying the field of a null object
2.3.1.
Code
2.4.
Java
2.4.1.
Output
2.5.
Null array
2.5.1.
Code
2.6.
Java
2.6.1.
Output
2.7.
A modifying array that is initially null
2.7.1.
Code
2.8.
Java
2.8.1.
Output
2.9.
Adding null to ConcurrentHashMap
2.9.1.
Code
2.10.
Java
2.10.1.
Output
2.11.
Throwing null
2.11.1.
Code
2.12.
Java
2.12.1.
Output
3.
Detection for NullPointerException
3.1.
Null Check
3.1.1.
Code
3.2.
Java
3.2.1.
Output
3.3.
Use ternary operator
3.3.1.
Code
3.4.
Java
3.4.1.
Output
3.5.
Keep a check on the arguments of the method
3.5.1.
Code
3.6.
Java
3.6.1.
Output
4.
How to Fix NullPointerException
5.
How to Avoid NullPointerException
6.
Frequently Asked Questions
6.1.
What do you mean by the NullPointerException in Java?
6.2.
How do you pass a NullPointerException in Java?
6.3.
How to handle NullPointerException for list string in Java?
6.4.
What results in the main thread Java Lang NullPointerException exception?
6.5.
How can NullPointerException be prevented?
6.6.
What can we do to prevent Java's NullPointerException and null checks?
6.7.
What state is NullPointerException in?
7.
Conclusion
Last Updated: Apr 3, 2024
Medium

How to solve exception in thread main java.lang.nullpointerexception?

Author Manan Singhal
0 upvote

Introduction

This article will look at the most common java exception, i.e., an exception in thread main java lang nullpointerexception. It is a type of Runtime Exception.

This is the most common exception you have encountered. You may also agree that NullPointerException is a hassle for most java developers. Still, there isn't much we can do about it because this is the price we must pay for convenient or unavoidable null references.

NullPointerException

Must Read, Multithreading in java , Duck Number in Java, Multithreading in Python

Reasons for NullPointerException

Consider a Class Data, now we use this class and see what the possible reasons we got stuck with an error: Exception in thread main Java lang nullpointerexception are
 

/* Exception in thread main java lang nullpointerexception */
public class Data {
    
    String data1;
    int data2;
 
    public Data() {}
 
    public Data(String data1, int data2) {
        this.data1=data1;
        this.data2=data2;
    }
    public String getData1() {
        return data1;
    }
    public void setData1(String data1) {
        this.data1 = data1;
    }
    public int getData1() {
        return data2;
    }
    public void setData1(int data2) {
        this.data2 = data2;
    }
}
Reasons

Calling the instance method of a null object

Code

  • Java

Java

public class CodingNinjas {
   public static void main(String[] args) {
       Data data = null;
       String data1 = data.getData1();
       System.out.println("Data class: "+ data1);
   }
}

Output

As we can see, that data is null at the time of printing data1; that's why we are getting an error: exception in thread main java lang nullpointerexception.

Modifying the field of a null object

Code

  • Java

Java

public class CodingNinjas {
   public static void main(String[] args) {
       Data data = null;
       String data1 = data.data1;
       System.out.println("Data class: "+ data1);
   }
}

Output

As we can see, that data is null at the time of printing data1; that's why we are getting an error: exception in thread main java lang nullpointerexception. This is very much similar to the previous one.

Also see,  Swap Function in Java

Null array

Code

  • Java

Java

public class CodingNinjas {
   public static void main(String[] args) {
       Data[] data = null;
       int length = data.length;
       System.out.println("Length: "+ length);
   }
}

Output

As we can see, the array data is null; that is, at the time of printing the length of an array, it was not even initialized. That's why we get an error: exception in thread main java lang nullpointerexception.

A modifying array that is initially null

Code

  • Java

Java

public class CodingNinjas {
   public static void main(String[] args) {
       Data[] data = null;
       System.out.println("Item: "+ data[1]);
   }
}

Output

As we can see, the array data is null; that is, at the time of printing the elements of an array, it was not even initialized. That's why we get an error: exception in thread main java lang nullpointerexception.

Try and compile on online java compiler.

Adding null to ConcurrentHashMap

Code

  • Java

Java

public class CodingNinjas {
   public static void main(String[] args) {
       ConcurrentHashMap<String, String> map = new ConcurrentHashMap<>();
       map.put(null, "SomeData");
   }
}

Output

You can not assign the key to null in ConcurrentHashMap, causing the program to throw: an exception in thread main java lang nullpointerexception.

Throwing null

Code

  • Java

Java

public class CodingNinjas {
   public static void main(String[] args) {
       throw null;
   }
}

Output

You got an error: exception in thread main java lang nullpointerexception.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Detection for NullPointerException

NullPointerException is simpler to recognize. Go to that line number and investigate what might be causing the NullPointerException by checking the exception trace, which will provide the class name, method name, and line number.

Detection

Null Check

Code

  • Java

Java

/* Preventing: Exception in thread main java lang nullpointerexception */
public class CodingNinjas {
   public static void main(String[] args) {
       Data data = null;
       if (data != null) {
           String data1 = data.getData1();
           System.out.println("Data class: "+ data1);
       }
   }
}

Output

As we can see, before performing any method calls on Class Data, we check that it is not null and then perform operations on it. This way, you can avoid exception in thread main java lang nullpointerexception from occurring.

Use ternary operator

Code

  • Java

Java

/* Preventing: Exception in thread main java lang nullpointerexception */
public class CodingNinjas {
public static void main(String[] args) {
Data[] data = null;
String data1 = data == null ? data.getData1() : "";
System.out.println("Data class: "+ data1);
}
}

Output

We can see that we are assigning value for a name if it is null or non-null. This way, you can avoid exception in thread main java lang nullpointerexception from occurring.

Keep a check on the arguments of the method

Code

  • Java

Java

/* Preventing: Exception in thread main java lang nullpointerexception */
public class CodingNinjas {
   public static void main(String[] args) {
       Data[] data = null;
       String data1 = null;
       if (data.getData1() == null) {
           data1 = "";
       }
       else {
           data1 = data.getData1();
       }
       System.out.println("Data class: "+ data1);
   }
}

Output

We can see that we are assigning value for a name if it is null or non-null. This way, you can avoid exceptions in thread main java lang nullpointerexception from occurring. This method is similar to the ternary operator.

How to Fix NullPointerException

To fix NullPointerException you follow these steps:

  1. Identify the Cause: Determine which variable or object is null when the NullPointerException occurs. Trace the code to find the exact location where the null reference is being accessed.
  2. Check for Null: Before accessing any variable or object, ensure that it is not null. Use conditional statements (e.g., if statements) or null checks (e.g., Objects.requireNonNull()) to handle null cases gracefully.
  3. Handle Exceptions: Use try-catch blocks to catch NullPointerExceptions when necessary. This allows you to handle the exception gracefully, such as displaying an error message to the user or logging the error for debugging purposes.
  4. Use Optional: If applicable, consider using Java's Optional class to handle potentially null values more effectively. Optional provides methods for safely accessing and manipulating values without risking NullPointerExceptions.
  5. Debugging: Utilize debugging tools and techniques to identify and resolve the root cause of the NullPointerException. Debuggers, logging, and systematic code inspection can help pinpoint and fix null reference issues.

How to Avoid NullPointerException

To avoid NullPointerException you follow these practices:

  • Initialize Variables: Always initialize variables and objects before accessing them. This ensures that they have valid values and reduces the likelihood of encountering NullPointerExceptions.
  • Null Checking: Implement null checks wherever necessary to verify that variables or objects are not null before using them. This can be done using if statements, ternary operators, or utility methods like Objects.requireNonNull().
  • Defensive Coding: Practice defensive coding by anticipating potential null references and handling them appropriately. This involves validating inputs, checking return values from methods, and handling null cases gracefully.
  • Use Optional: Consider using Java's Optional class to represent potentially null values more explicitly. Optional provides methods for safer and more concise handling of nullable values, reducing the risk of NullPointerExceptions.
  • Code Reviews: Conduct regular code reviews to identify and address null reference issues. Peer review can help catch potential NullPointerExceptions before they manifest in production code.
  • Testing: Perform thorough testing, including unit tests and integration tests, to validate the behavior of your code under various scenarios, including null inputs and references. Testing helps uncover and address NullPointerExceptions early in the development process.

Hashcode Method in Java

Frequently Asked Questions

What do you mean by the NullPointerException in Java?

The null pointer exception in Java is a runtime exception that gets triggered when the java program tries to use the object reference that contains the null value or not initialized variable.

How do you pass a NullPointerException in Java?

Passing a null reference to a method or accessing a member of a null object can result in a NullPointerException in Java.

How to handle NullPointerException for list string in Java?

Handle NullPointerException for a list of strings in Java by checking if the list itself is null before accessing its elements or invoking methods on it.

What results in the main thread Java Lang NullPointerException exception?

When a reference variable is accessed and does not point to any objects, NullPointerException is raised. Use a try-catch block or an if-else condition to determine whether a reference variable is null before dereferencing it to fix this error.

How can NullPointerException be prevented?

Before using any objects, we must ensure they have all been initialized correctly to prevent the NullPointerException. Before requesting a method or a field from an object, we must first ensure the referenced object is not null when we declare a reference variable.

What can we do to prevent Java's NullPointerException and null checks?

The Optional class was introduced in Java 8 and provided a nice solution to prevent NullPointerExceptions. Using Optional to encapsulate the potential null values, you can pass or return it safely without being concerned about the exception.

What state is NullPointerException in?

The Java Null Pointer Exception (NPE) extends Runtime Exception and is a checked or unchecked exception. We can try using a try, catch or finally block to handle Null Pointer Exception.

Conclusion

In the article, we have discussed detecting the most common exception in Java, i.e., an exception in thread main java lang nullpointerexception. We hope that this article will help you solve your error, and if you want to learn about exceptions in Java, check out our other blogs on this topic:

Refer to our guided paths on Coding Ninjas Studio to learn about Data Structure and Algorithms, Competitive Programming, JavaScript, etc. Enroll in our courses and refer to our mock test available. Have a look at the interview experiences and interview bundle for placement preparations.

Happy Coding!

Previous article
Exception Handling with Method Overriding in Java
Next article
Decoding throw and throws keywords in Exception Handling|Part-4
Live masterclass