Null values of Strings and Integers in Java

tania picture tania · Jan 26, 2013 · Viewed 7.9k times · Source
public class Test {
    public static void main(String[] args) {

        String s = null;
        String s1 = null;
        Integer i = null;
        Integer i1 = null;

        System.out.println(s+i);
        System.out.println(i+s);
        System.out.println(s+s1);

        try {
            System.out.println(i+i1);
        } catch (NullPointerException np) {         
            System.out.print("NullPointerException");       
        }
    }

}

The question is simple - why do I receive a NullPointerException only at the last line?

Answer

NPE picture NPE · Jan 26, 2013

Your code makes use of two different additive operators. The first three lines use string concatenation, whereas the last one uses numeric addition.

String concatenation is well-defined to turn null into "null":

  • If the reference is null, it is converted to the string "null" (four ASCII characters n, u, l, l).

Hence there is no NPE.

Adding two Integer objects together requires them to be unboxed. This results in the null reference being dereferenced, which leads to the NPE:

  • If r is null, unboxing conversion throws a NullPointerException