22

I have the following code

System.out.println("" + null);

and the output is null.
How does Java do the trick in string concatenation?

giannis christofakis
  • 8,201
  • 4
  • 54
  • 65
oshai
  • 14,865
  • 26
  • 84
  • 140

3 Answers3

30

Because Java converts the expression "A String" + x to something along the lines of "A String" + String.valueOf(x)

In actual fact I think it probably uses StringBuilders, so that:

"A String " + x + " and another " + y

resolves to the more efficient

new StringBuilder("A String ")
    .append(x)
    .append(" and another ")
    .append(y).toString()

This uses the append methods on String builder (for each type), which handle null properly

oxbow_lakes
  • 133,303
  • 56
  • 317
  • 449
  • IIRC, it doesn't actually hit up `String.valueOf(y)`. There are overloads of `StringBuilder.append` for every possible type, and `append(Object)` handles the null directly. You can replace the "I think it probably" with "it" though. – Mark Peters Nov 16 '10 at 21:54
  • Yes - I'm old skool, I'm afraid - from back in the day when string concatenation was unperformant! – oxbow_lakes Nov 16 '10 at 21:56
  • 2
    Just inspected the code for `append(Object)`, and it does in fact delegate to `String.valueOf()`. *Inside* the method though. So they boil down to the same calls. – Mark Peters Nov 16 '10 at 21:59
9

Java uses StringBuilder.append( Object obj ) behind the scenes.

It is not hard to imagine its implementation.

public StringBuilder append( Object obj )
{
   if ( obj == null )
   {
       append( "null" );
   }
   else
   {
       append( obj.toString( ) );
   }

   return this;
}
Alexander Pogrebnyak
  • 44,836
  • 10
  • 105
  • 121
  • Link to implementation: http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/StringBuilder.java#170 – Steve Chambers Sep 26 '17 at 09:18
4

The code "" + null is converted by the compiler to

new StringBuffer().append("").append(null);

and StringBuffer replaces null with the string "null". So the result is the string "null".

Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276
  • 2
    Just a small correction; it's now StringBuilder not StringBuffer. Thread safety isn't a concern with String concatenation (over the lifetime of the builder anyway). – Mark Peters Nov 16 '10 at 22:00
  • Why would one want/need to write `"" + null` instead of just `"null"`? Is that example just for academic exercise? – tony19 Jan 09 '14 at 03:50
  • @user46874: i think it must have been an experiment to see how nulls get printed. – Nathan Hughes Jan 09 '14 at 14:55