by BehindJava

How to Avoid java.lang.NullPointerException in Java

Home » interview » How to Avoid java.lang.NullPointerException in Java

In Java, the null value is used to denote that a reference variable has no value. The use of null values is common in design patterns like singleton patterns. In particular circumstances, Java throws the Null Pointer Exception - see NullPointerException.

Typically, the null value is used to denote that a reference variable has no value. Second, we require null values for collections like trees and linked lists to denote null nodes. The use of null values is common in design patterns like singleton patterns.

Note that Java has several applications for the null value. In particular circumstances, Java throws the Null Pointer Exception.

Here are a few examples of the scenarios:

  1. Using a null object, the method was called.
  2. The null object’s field or a data member can be accessed or changed.
  3. Supplying a method with an empty parameter.
  4. Determining a null array’s length.
  5. Gaining access to a null array’s index.
  6. A null object being synchronized.
  7. Throwing a null object.

The class RuntimeException is an extension of the Null Pointer Exception.

Example of NullPointerException

public class BehindJava {

	public static void main(String[] args) {
		String s = null;
        //String s = "Behind Java";
		int len = s.length();
		System.out.println("Length of the String:" + len);
	}
}

Output:

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.length()" because "s" is null
	at ds.BehindJava.main(BehindJava.java:7)

How to avoid java.lang.NullPointerException

The following are a few suggestions for avoiding NullPointerException:

  • Use the equals() and equalsIgnoreCase() methods on a String literal rather than on an undefined object that might be null.
  • To get the same outcome, use function valueOf() { [native code] }() rather than function toString() { [native code] }().
  • Use the Java annotations @Nullable and @NotNull.
  • Optional class has been introduced from Java 8 to avoid NullPointerException.