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.

0

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

5 Comments

In this specific case, you are correct. However in the more general case of printing null strings: docs.oracle.com/javase/6/docs/api/java/io/… & docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.1.11
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 it depends on implementation really besides append(null) also needs to append "null"
@ratchetfreak Not all the JDK convert the string concatenation to a StringBuilder expression.
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.
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

1 Comment

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
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();
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.