1

Possible Duplicate:
Concatenating null strings in Java

I'm just wondering if someone can explain why does the following code works the way it does:

String a = null;
String b = null;
String c = a + b;
System.out.println(c.toString());

This prints "nullnull" to the console.

I was kind of expecting that the operation + would thrown an exception or, to a lesser degree, that "c" would be null.

Community
  • 1
  • 1
Tiago
  • 934
  • 6
  • 15

3 Answers3

9

because that code compiles to

String c = new StringBuilder().append(a).append(b).toString();

and StringBuilder.append(a) appends the result of String.valueof(a) which is "null" if a is null

ratchet freak
  • 47,288
  • 5
  • 68
  • 106
  • In this specific case, you are correct. However in the more general case of printing null strings: http://docs.oracle.com/javase/6/docs/api/java/io/PrintStream.html#print%28java.lang.String%29 & http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.1.11 – Colin D Apr 12 '12 at 18:48
  • It is not correct, in my case it convert that line in `String c = new StringBuilder(String.valueOf(a)).append(b).toString();`. The real reason is the `String.valueOf(Object)` implementation. – dash1e Apr 12 '12 at 18:49
  • @dash1e it depends on implementation really besides `append(null)` also needs to append "null" – ratchet freak Apr 12 '12 at 18:54
  • @ratchetfreak Not all the JDK convert the string concatenation to a StringBuilder expression. – dash1e Apr 12 '12 at 19:03
  • The way the compiler transform the concatenation expression is not the reason of the result. Every compiler can achieve that result as prefer. The right answer is the @Joni Salonen answer. – dash1e Apr 12 '12 at 19:11
2

"String conversion," required by the concatenation operator, mandates that null values are to be mapped to the four characters null whenever a string representation is needed.

Spec for string conversion: http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.1.11

Spec for string concatenation: http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.18.1

Joni
  • 108,737
  • 14
  • 143
  • 193
  • Thanks for the reply, perfect. I voted to close the question, since a duplicate was found otherwise yours would be the answer that I would accept – Tiago Apr 12 '12 at 18:47
0

When java find a null reference during the string concatenation convert it to the string "null". So "nullnull" is the right result.

Before concatenation for every object Java call

java.lang.String.valueOf(Object)

and if you look at the source code of that method you find this

public static String valueOf(Object obj) {
  return (obj == null) ? "null" : obj.toString();
}
dash1e
  • 7,677
  • 1
  • 30
  • 35