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.
Reasons for the Null Pointer Exception
The possible scenarios where the null pointer exception can be thrown are as follows:
1. 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
2. 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
In Java, null represents the absence of a value or an uninitialized object reference. It helps handle optional data, avoid unnecessary object creation, and indicate missing values in collections or APIs. However, improper handling can lead to NullPointerException.
Example:
Java
Java
class Student { String name; }
public class Main { public static void main(String[] args) { Student student = null; // No object assigned if (student == null) { System.out.println("Student object is null"); } } }
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.
Method 1 - 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
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.
Can we override NullPointerException in Java?
No, we cannot override NullPointerException, but we can handle it using a try-catch block. Since it extends RuntimeException, we can create a custom exception by extending it, but overriding system-defined exceptions is not possible.
Is NullPointerException checked or unchecked?
NullPointerException is an unchecked exception because it extends RuntimeException. It is not checked at compile-time, meaning the compiler does not force handling it. It occurs at runtime when an application attempts to use null where an object is required.
Conclusion
NullPointerException in Java is a common runtime exception that occurs when an application attempts to access an object reference that is null. It is an unchecked exception, meaning it is not enforced at compile time. Proper handling of null values using null checks, Optional class, or exception handling can help prevent unexpected crashes.