How to resolve the java.lang.NullPointerException

In Java, the java.lang.NullPointerException is thrown when a reference variable is accessed (or de-referenced) and is not pointing to any object. This error can be resolved by using a try-catch block or an if-else condition to check if a reference variable is null before dereferencing it.

In some cases, the compiler prevents this exception with the compile-time error “The variable might not have been initialized” when a null reference variable is passed as an argument of a method:

String s;
foo(s);  // Compiler gives an error.

However, the compiler does not give this error when null is directly passed to a function; ​however​, there is a higher chance of it throwing a NullPointerException:

foo(null);  // Higher probability of an exception

Real-world example

Now let’s enhance our understanding with a real-world example

public class NullPointerExample {
public static void main(String[] args) {
String s = "example";
// Calling methods with null argument
foo(null);
bar(null);
}
// Using a try-catch block:
static void foo(String x){
try {
System.out.println("First character: " + x.charAt(0));
} catch(NullPointerException e) {
System.out.println("NullPointerException thrown!");
}
}
// Using if-else condition:
static void bar(String x){
if(x != null)
System.out.println("First character: " + x.charAt(0));
else
System.out.println("NullPointerException thrown!");
}
}

Upon running this code, we will get the java.lang.NullPointerException error because we are calling the function with a null argument. Now let's resolve it.

public class NullPointerExcept {
public static void main(String[] args) {
String s = "example";
// Calling methods with valid argument
foo(s); // Resolved: Passing a valid string "example"
bar(s); // Resolved: Passing a valid string "example"
}
// Using a try-catch block:
static void foo(String x){
if (x == null) {
System.out.println("String is null!");
return;
}
System.out.println("First character: " + x.charAt(0));
}
// Using if-else condition:
static void bar(String x){
if(x == null) {
System.out.println("String is null!");
return;
}
System.out.println("First character: " + x.charAt(0));
}
}

We just solved the issue by passing a valid string argument to the function.

Copyright ©2024 Educative, Inc. All rights reserved