Search code examples
javanullpointerexceptionnullconcatenation

Behaviour of null in Java


This probably looks duplicate of other questions on SO. But, I was wondering the way Java treat null.

Eg:

public class Work {
    String x = null;
    String y;
    Integer z;

    public static void main(String arg[]) {
        Work w = new Work();
        w.x = w.x + w.y; // work Line 1
        w.x = w.x + w.y + w.z; // work Line 2
        w.z = w.z + w.z; // NullPointerException Line 3
        System.out.println(w.x.charAt(4));
    }
}

Commenting Line 3 prints n whereas uncommenting throws NullPointerException. If I'm not wrong for Line 1 and Line 2, it being implicitly type cast to String. But, what happen to Line 3 ?


Solution

  • String has a lot of special allowances in Java, for better or for worse. The specification dictates that null gets converted to the string "null" when converted to a string, e.g. by string concatenation (which implicitly calls toString() on other operands). So adding null to a string works by virtue of the language spec saying so.

    Based on this your first two lines will result in

    w.x = "null" + "null";
    w.x = "nullnull" + "null" + "null";
    

    In line 3 you get a different phenomenon, in this case auto-boxing and -unboxing. To ease the disconnect between primitive types and their respective wrapper classes you can apply arithmetic operators to wrapper classes, which prompt their values to be unboxed, operated on, and the result being boxed again. And this is where the NullReferenceException happens, because w.z is still null and thus cannot be unboxed. In essence:

    w.z = w.z + w.z
    

    is turned by the compiler into:

    w.z = Integer.valueOf(w.z.intValue() + w.z.intValue());
    

    and the call to intValue() is what fails because w.z is null here.

    Prior to Java 5 this is what you had to write yourself if you wanted to have calculations on Integer objects.