Trusted answers to developer questions

How to resolve the java.lang.NullPointerException

Get the Learn to Code Starter Pack

Break into tech with the logic & computer science skills you’d learn in a bootcamp or university — at a fraction of the cost. Educative's hand-on curriculum is perfect for new learners hoping to launch a career.

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.

RELATED TAGS

exception handling
null
pointer
resolve
java
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?