Note that the first three operators of the + operator are related to string concatenation. Only the latter is the actual numerical sum. When string concatenation is involved (where the s variable is involved), the Java compiler uses some smart tricks to improve performance. It replaces the + operator with StringBuilder . For example, your first line is translated into:
StringBuilder tmp = new StringBuilder(); tmp.append(s); tmp.append(i); System.out.println(tmp);
StringBuilder null is friendly, so no matter what you pass as an argument, it nicely replaces it with the string "null" .
In the last line, the situation is different. There you refer to two Integer objects. The only thing the JVM can do here is to unzip them ( i.intValue() ) and do the actual calculation. Unboxing null raises a NullPointerException .
Tomasz Nurkiewicz Jan 26 '13 at 16:27 2013-01-26 16:27
source share