Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String concatenation with Null

Tags:

I have the following code

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

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

like image 622
oshai Avatar asked Nov 16 '10 21:11

oshai


2 Answers

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

like image 141
oxbow_lakes Avatar answered Sep 21 '22 15:09

oxbow_lakes


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;
}
like image 24
Alexander Pogrebnyak Avatar answered Sep 19 '22 15:09

Alexander Pogrebnyak