Winston Gutkowski wrote:@Janet: Specifically, println() uses String.valueOf(Object) to determine what string to print out, and if you look at the docs for that method, you'll read precisely the behaviour you're seeing.
I have to nitpick a little bit about that statement

This would have been 100% accurate if the line of code at
line12 would have been
In this case the overloaded version of the
print() method taking an
Object parameter would be executed. And the implementation of this method uses indeed
String.valueOf(Object) to create a string representation of the
Object parameter. And that method will (as Henry mentioned) check for
null; it returns
"null" in that case,
object.toString() otherwise (that illustrates why the
null check is so important). So if you would use the statement
System.out.print(s); (on
line12) in the above code snippet, the output will be
"nullbc".
But the above code snippet uses a different statement
In this case concatenating
s with
" " happens first and then the result (a
String object) will be passed to the overloaded version of the
print() method taking an
Object parameter. So now a new question arises: why does the concatenation
s + " " not throw a NullPointerException? Luckily the answer is very simple (and already discussed). The same method
String.valueOf(Object) is used here as well. So
s + " " is executed as
String.valueOf(s) + " ". And that's why no NPE will be thrown. So if you would use the statement
System.out.print(s); (on
line12) in the above code snippet, the output will be
"null b c ".
And here is a final note. You know two different ways to concatenate strings: either use the concatenation operator
+ or use the
concat(String) method of the
String class. Although both ways will concatenate, there are a few important differences:
if a is null, then a.concat(b) throws a NullPointerException but a + b will not; so if you would use the statement System.out.print(s.concat(" ")); (on line12) in the above code snippet, a NullPointerException will be thrownif b is null, then b.concat(a) throws a NullPointerException but a + b will not; so if you would use the statement System.out.print(" ".concat(s)); (on line12) in the above code snippet, a NullPointerException will be thrown; using statement System.out.print(" " + s); (on line12) in the above code snippet will result in the output " null b c"the concat() method only accepts String values while with the + operator you can append all other types (primitive data types and reference types) as well; using statement System.out.print(s.concat(1)); (on line12) in the above code snippet results in a compiler error; if you would use the statement System.out.print(s + 1); (on line12) in the above code snippet, the output will be "null1b1c1"
Hope it helps!
Kind regards,
Roel