简体   繁体   中英

String concatenation with Null

I have the following code

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

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

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 StringBuilder s, 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

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

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".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM