While reading this question, I remembered a bug in a program I wrote while I was first learning java that took me forever to locate and essentially boiled down to the following behavior:
String s1 = "This was a triumph";
String n1 = null;
System.out.println(s1 + n); // prints "This was a triumphnull"
Some other notable examples (and perplexing counter-examples) of similar behavior:
// "nullThis was a triumph", coercion happens commutatively
System.out.println(n1 + s1);
// as per above question, println explicitly converts null Strings to "null"
System.out.println(n1);
// similar result
System.out.println(String.valueOf(n1));
// NullPointerException (!!); null not silently converted to "null"
// note that this is the kind of thing I expected to occur for the other examples
// when I wrote the buggy code in the first place
System.out.println(n1.toString());
While I suppose I technically understand this behavior, I definitely don't grok it, so my question is:
- From a language design standpoint, why does java convert a null String to a "null" String in so many cases?
- Why doesn't it do so in the cases in which...it doesn't do so?
EDIT
I appreciate the answers so far, but I just want to clarify that my confusion largely originates from how null Strings are treated so differently in this respect than other null Objects. For example:
Integer i1 = 42;
Integer n2 = null;
// Both produce NullPointerExceptions:
Integer.valueOf(n2);
System.out.println(i1 + n2);
I also want to reemphasize that a NullPointerException is the kind of behavior I expected, which is why I was so confused about the null/"null" String conversion in the first place.