oshai oshai -5 years ago 150
Java Question

String concatenation with Null

I have the following code

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

and the output is

How does Java do the trick in string concatenation?

Answer Source

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(" and another ")

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download