Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
In Java, the Null Pointer Exception (NPE) is one of the most common runtime errors that occurs when an application attempts to use an object reference that has not been initialized, or has been set to null. This exception can happen when trying to access methods or fields of an object that doesn't point to any memory location. Understanding how and when NPE occurs is crucial for writing robust and error-free Java programs. In this blog, we’ll explore the causes of Null Pointer Exceptions, how to prevent them, and best practices for handling them in Java applications.
What is a Null Pointer Exception in Java?
A Null Pointer Exception (NPE) in Java occurs when the JVM attempts to access or modify an object or its methods/fields through a reference that is null. This means the reference does not point to any memory location or object, leading to the exception. It commonly happens when trying to call methods or access attributes on an uninitialized object, or when a method returns null and it is improperly accessed. NPE is a runtime exception, and if not handled properly, it can cause the program to crash.
Possible Scenarios for the Null Pointer Exception
The possible scenarios where the null pointer exception can be thrown are as follows:
When the Method is Invoked Using a Null Object.
If we invoke some methods on the null object, Java throws the NullPointerException.
Example
Java
Java
public class Main{
// returns sum of two numbers int sum(int a , int b) { return a + b; } public static void main(String[] args) { Main m = null; // intitialised the object with null value // Invoking the method sum on the null object. System.out.println(m.sum(10, 20)); } }
You can also try this code with Online Java Compiler
When a Program Tries to Modify the Null Objects Field
If any program tries to modify the null object field, the NullPointerException is thrown.
Example
Java
Java
public class Main{ int val = 10; public static void main(String[] args) { Main m = null; // intitialised the object with null value // It tries to read the data on the null object System.out.println(m.val); } }
You can also try this code with Online Java Compiler
For Java developers, avoidance of the NullPointerException is an important task. Unlike other programming languages, Java does not provide any method to check for NullPointerException.
To avoid the null pointer exceptions, you need to ensure that every object must be initialised with some value before you use them.
We can consider the following scenarios to deal with the NullPointerException.
Scenario1(String Comparison with Literals)
In this case, we compare a string to a literal.
If the String object is set to null, it throws a NullPointerException, as shown below.
Example1
Java
Java
public class Main{ public static void main(String[] args) { // the string value is initialized to null String s = null; try{ // we are checking if the string is equal to "hello" or not // if the string is found to be null, then the NullpointerException will be thrown if(s.equals("hello")) { System.out.println("The string is \"hello\""); } else{ System.out.println("The string is not \"hello\""); } } catch(NullPointerException e){ System.out.println("NullpointerException"); } } }
You can also try this code with Online Java Compiler
We can avoid this null pointer exception by invoking the equals() method from the literal.
Let’s see how we can do this in the below example.
Example2
Java
Java
public class Main{ public static void main(String[] args) { // the string value is initialized to null String s = null; try{ // we are checking if the string is equal to "hello" or not, by invoking the equals method from the literal "hello" if("hello".equals(s)) { System.out.println("The string is \"hello\""); } else{ System.out.println("The string is not \"hello\""); } }
Here, we check the arguments passed to a method for null values. If the arguments are properly checked, then only we execute the body of the function. However, if the arguments are not legitimate, it throws an IllegalArgumentException.
Example
Java
Java
public class Main{ // method getString() returns the string argument public static String getString(String s) { // if the string is null it informs the calling method that the argument is illegal. if(s == null) throw new IllegalArgumentException("The argument is null"); return s; } public static void main(String[] args) {
String s = null; try{ // It throws an IllegalArgumentException System.out.println(getString(s)); } catch(IllegalArgumentException e) { System.out.println("IllegalArgumentException"); }
s = "Hello there!";
try{ // It prints the string System.out.println(getString(s)); } catch(IllegalArgumentException e) { System.out.println("IllegalArgumentException"); }
} }
You can also try this code with Online Java Compiler
We can also use the ternary operator to avoid the NullPointerException. Using the ternary operator, we first check the boolean expression, and if it is found to be true, then the first value will be returned. Otherwise, the second value will be returned.
Example
Java
Java
public class Main{ public static void main(String[] args) { String s = null;
// as s == null, it initializes the variable with the empty string String ans = (s == null) ? "" : s; System.out.println(ans);
// as the s != null, it initializes the variable the variable with the whole string. s = "hello there"; ans = (s == null) ? "" : s; System.out.println(ans); } }
You can also try this code with Online Java Compiler
A NullPointerException is caused when an application attempts to use a null reference to access methods, fields, or elements of an object.
How do I fix NullPointerException in Java?
Fix a NullPointerException by ensuring that references are properly initialized, checking for null before accessing methods/fields, and using Optional where appropriate.
Should I catch a NullPointerException in Java?
Catching a NullPointerException is generally not recommended; instead, focus on preventing it through proper null checks, initialization, and safe method calls.
What is the best way to handle NullPointerException?
The best way to handle a NullPointerException is to prevent it by checking for null values, using Optional, and applying defensive programming practices.
Conclusion
In this article, we have extensively discussed the Null Pointer Exception in Java.
We started with the basic introduction of the blog. we coved some of the important key points:-
What is the Null Pointer Exception in Java
The cases in which we can get the Null pointer Exception
We discussed five cases.
The method is invoked with null objects.
The program tries to modify the null object.
A null object is passed to the method.
Operate on the null array object.
Synchronise over a null object.
Avoidance of the Null Pointer Exception.
We discussed three different scenarios, string comparison, checking arguments and use of the ternary operators.
We hope that this blog has helped you enhance your knowledge regarding Null Pointer Exception in Java and if you would like to learn more, check out our articles on Converting Java String to Int, Char to Int in Java. Do upvote our blog to help other ninjas grow.