Users often mistakenly try to access or de-reference variables that are not pointing to any object referring to as null or nothing. This error is known as NullPointerException, a runtime exception in Java. In the article, we will be discussing the Java NullPointerException and how users can fix this exception.
What is meant by NullPointerException in Java?
In Java, the Null pointer exception is a type of Runtime exception that arises when users try to access a variable that does not refer to any object, or in other words, refers to null or nothing, also known as the "java.lang.NullPointerException." The application code does not need to catch and handle the Null Pointer Exception in Java.
What causes NullPointerException in Java?
In the definition of NullPointerException, we discussed that NullPointerException refers to a runtime exception in Java, occurring due to a trouble in application code where users attempt to access or modify an uninitialized object.
Specifically, this indicates that the referred Java object does not point to anything and contains a null value.
The following points are the most typical exceptional cases for the Java NullPointerException occurrence:
- When users call a method on a null object to give rise to NullPointerException
- When users try to access or modify a null object's properties can create When users try to access
- When users try to access the index element of a null object, such as in an array, the NullPointerException occurs
- If users pass null parameters to a method, this can give rise to NullPointerException
- The NullPointerException may also occur due to inappropriate configuration for dependency injection frameworks such as String.
- When users throw "synchronized" on a null object
- Lastly, if users throw null from a method that arises an exception
NullPointerException Examples:
There are several reasons for the NullPointerException. In the following section of this article, we will discuss these reasons with examples and their solutions:
Example 1: Java NullPointerException when users access or modify the field of the null object:
Code Snippet:
public class Main {
public int a = 9;
public static void main(String[] args) {
Main i = initT();
int x = i.a;
}
private static Main initT() {
return null;
}
}
Output:
Explanation:
The Java engine is throwing NullPointerException in statement int x = i.a; because "i" is null here (since initT() function is returning a null).
Solution:
public class Main {
static void myMethod(int demo) {
System.out.println(demo + 3);
}
public static void main(String[] args) {
int x;
x = 10;
System.out.println("The multiplication is = " + 8*5);
System.out.println("The multiplication is = " + x*3);
}
}
Output:
Explanation:
If we apply simple multiplication with no null value in the variable, we can get the exact answer of the multiplication. Here, we will not return null in the return statement. The output is 40 and 30.
Example 2: When users pass null in the method argument gives rise to Java NullPointerException:
Code Snippet:
public class Demo {
public static void main(String[] args) {
samp(null);
}
public static void samp(String a) {
System.out.println(a.toLowerCase());
}
}
Output:
Explanation:
In the above code snippet, we are calling a null method argument. It is one of the most typical occurrences of the "java.lang.NullPointerException."
Solution:
public class Main {
static void myMethod(String demo) {
System.out.println(demo + " XYZ");
}
public static void main(String[] args) {
myMethod("A");
myMethod("B");
myMethod("C");
}
}
Output:
Explanation:
In the above code snippet, we provided the solution on how to ignore the NullPointerException in Java program. We have simply passed the names in double quotes instead of a null method argument. This will not return a NullPointerException.
Example 3 - Using the length() method on a null string object:
Code Snippet:
public class example {
private static void leng(String s) {
System.out.println(s.length());
}
public static void main(String args[]) {
String demo = null;
leng(demo);
}
}
Output:
Explanation:
In the above code snippet, we used the "leng()" method that calls the length() method of the Java String without checking whether we are calling a null object before calling the method.
Since we have passed a value of the string from the Java main() method, which is null, the Java engine will show the NullPointerException while running the above code.
Solution:
public class Main {
public static void main(String[] args) {
String demo = "null";
System.out.println(demo.length());
}
}
Output:
Explanation:
In the solution, we have passed the null as the string with double quotes. Thus, it will not return a NullPointerException. Instead it will return the length of that string, which is “4.”
Example 4: NullPointerException when calling an instance method:
Code Snippet:
public class Demo {
public static void main(String[] args) {
Demo i = initT();
i.samp("NullPointerException");
}
private static Demo initT() {
return null;
}
public void samp(String x) {
System.out.println(x.toLowerCase());
}
}
Output:
Explanation:
The Java engine throws NullPointerException in statement int i.samp("NullPointerException"); because "i" is null here.
Solution:
public class Main {
String samp = "Hello";
public static void main(String[] args) {
Main myObj = new Main();
System.out.println(myObj.samp);
}
}
Output:
Explanation:
In the instance method of Java, we have used a variable samp that has a string. We will not pass any null value and the output will be that input string.
How to fix the Java NullPointerException?
The "java.lang.NullPointerException" is an unchecked exception in Java. Thus, users do not need to catch it. But users can prevent their Java program from null pointer exceptions using null checks and preventive coding practices.
Let us look at these code snippets, and the following ways will discuss how users can fix the Java NullPointerException cases:
If users write this code snippet:
public class Main{
private static void leng(String s){
System.out.println(s.length());
}
public static void main(String args[]){
String a = "Hello, this is Java and we are learning NullPointerException";
leng(a);
}
}
Output:
Instead of this code snippet which will give rise to NullPointerException:
public class Main{
private static void leng(String s) {
System.out.println(s.length());
}
public static void main(String args[]) {
String a = null;
leng(a);
}
}
Output:
Explanation:
As in the second code snippet, we have declared a variable as null, so when we use the String.length() method in Java, it will return a Java NullPointerException. Whereas, when we insert a string input in the variable "a" in the first code example, the length() method returns the length of the string.
Users can use the String.valueOf() instead of toString().Code snippet of String.valueOf() is as follows:
class Main {
public static void main(String[] args) {
Double a = 785864.834;
// Here, we convert the double to string
System.out.println(String.valueOf(a));
}
}
Output:
If we write the following two methods together, we can see the difference between String.valueOf and toString(), as:
Code Snippet of toString():
class Main {
public static void main(String[] args) {
Object a = null;
System.out.println(a.toString());
}
}
Output:
Code Snippet of String.valueOf():
class Main {
public static void main(String[] args) {
Object a = null;
System.out.println(String.valueOf(a));
}
}
Output:
Explanation:
In the above two code snippets, we are checking whether the Object is null or not, and the two methods in Java, i.e., String.valueOf() and toString(). To avoid NullPointerException, use the String.valueOf() instead of toString() that will throw java.lang.NullPointerException.
- Users can write methods that return empty objects instead of null wherever possible. For instance, they can use an empty string, empty list, etc. but should avoid null.
- To avoid NullPointerException, users can use these methods, namely containsKey(), contains(), and containsValue() defined in collection classes.
Conclusion:
Every Java programmer needs to avoid and fix a null point exception. Java does not include methods that check null pointer exceptions, but other programming languages provide them. This article discusses all the reasons and the solutions to fix Java NullPointerException.
But one significant point every user should remember is that they must check the external libraries they are using, do not return a reference containing any null value.