Is concatenating with an empty string to do a stri

2019-01-11 12:30发布

Let's say I have two char variables, and later on I want to concatenate them into a string. This is how I would do it:

char c1, c2;
// ...

String s = "" + c1 + c2;

I've seen people who say that the "" + "trick" is "ugly", etc, and that you should use String.valueOf or Character.toString instead. I prefer this construct because:

  • I prefer using language feature instead of API call if possible
    • In general, isn't the language usually more stable than the API?
    • If language feature only hides API call, then even stronger reason to prefer it!
      • More abstract! Hiding is good!
  • I like that the c1 and c2 are visually on the same level
    • String.valueOf(c1) + c2 suggests something is special about c1
  • It's shorter.

Is there really a good argument why String.valueOf or Character.toString is preferrable to "" +?


Trivia: in java.lang.AssertionError, the following line appears 7 times, each with a different type:

    this("" + detailMessage);

9条回答
走好不送
2楼-- · 2019-01-11 13:01

Your arguments are good; this is one of the more expressive areas of the Java language, and the "" + idiom seems well entrenched, as you discovered.

See String concatenation in the JLS. An expression like

"" + c1 + c2

is equivalent to

new StringBuffer().append(new Character(c1).toString())
                  .append(new Character(c2).toString()).toString()

except that all of the intermediate objects are not necessary (so efficiency is not a motive). The spec says that an implementation can use the StringBuffer or not. Since this feature is built into the language, I see no reason to use the more verbose form, especially in an already verbose language.

查看更多
闹够了就滚
3楼-- · 2019-01-11 13:01

The best way to know is to compile / decompile your code, I used Jad http://en.wikipedia.org/wiki/JAD_(JAva_Decompiler) for that, you will see that your expression was converted into

String s = (new StringBuilder()).append("").append(ci).append(c2).toString();

As you can see javac actually included append("") call, but its cost is negligible, noting is appended to internal StringBuilder buffer, you can check StringBuilder's source

查看更多
来,给爷笑一个
4楼-- · 2019-01-11 13:02

I prefer using String.valueOf for single conversions - but in your case you really want concatenation.

However, I would suggest that this version would remove all potential ambiguity:

String s = c1 + "" + c2;

That way there's no possibility, however remote, of someone considering whether c1 and c2 will be added together before the concatenation.

查看更多
登录 后发表回答