Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

exception handling
null
pointer
resolve
java

How to resolve the java.lang.NullPointerException

Educative Answers Team

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
svg viewer

Solution

public class NullPointerExcept {
	public static void main(String[] args) {
		String s = "abcd";

		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!");
	}
}

RELATED TAGS

exception handling
null
pointer
resolve
java
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring