JavaException handling

NPE

What is NPE

Java provides a special value called null to indicate that no value is assigned to a reference variable. The value can cause one of the most arisen exceptions - java.lang.NullPointerException. It occurs when a program attempts to use a reference type that has the null value. The exception is also known as NPE.

There are several common situations when it occurs:
  • invoking a method of a null object using the dot notation;
  • accessing or modifying a null object's field;
  • unboxing a null value;
  • and a lot of other cases.
To avoid NPE, the programmer must ensure that are the objects are initialized before the use.

NPE when calling methods and operations

As a regular reference, a variable of the type String can be null. If we invoke a method (using the dot notation) or apply an operation to such variable, the code throw NPE.

1) In the following code an uninitialized instance of String is created and then the method length() of it is invoked. The code throws NPE because the object str is actually null.

String str = null; // a reference type can be null

int size = someString.length(); // NullPointerException (NPE)

The same exception will occur if we will use uninitialized of any other reference type, not only String.

To avoid the exception we should check the string is null or not and then perform different code depending on the result. It's similar to the default value.

int size = str != null ? str.length() : 0; // if the string is empty, the size is 0

In the code above, when the given string is null, the size is 0. Here are no exceptions.

2) A very common situation is a comparison between a String variable and a literal.

String str = null;

if (str.equals("abc")) { // it throws NPE because str is null
    System.out.println("The same");
}

To avoid NPE we can call equals on literal rather than the object:

 String str = null;

if ("abc".equals(str)) { // no NPE here
    System.out.println("The same");
}

But what if we have two variables of the type String? Any of them may be null. In this case, we can use the special auxiliary class java.util.Objects.

String s1 = null;
String s2 = null;
        
if (Objects.equals(s1, s2)) {
    System.out.println("Strings are the same");
}

NPE when unboxing

The NPE may occur during unboxing a value. For instance, the following code throws the NPE.

Long val = null;
long unboxed = val; // NPE occurs here

To fix it, we can add a conditional statement like this:

long unboxed = val != null ? val : 0; // No NPE here

Conclusion

We consider some typical cases when NPE occurs. Of course, it may occur in many other situations. But the common rule - be careful when processing reference types. In the general case, to avoid the NPE we can use the condition statement to check the given variable. If it is null, depending on the solving task, it's possible to return a default value, do nothing or something else.
How did you like the theory?
Report a typo