Here's some simple Java code:
String s = new StringBuilder().append("a").append("b").append("c").toString();
I compile it with JRE 1.6, and I observe the following in the decompiled class file:
String s = "a" + "b" + "c";
I had the following questions:
- Why does the compiler choose '+' over StringBuilder?
- Do we have any official Java specification that justifies this behavior?
- Does it really make sense to use StringBuilder in such cases, where we know compiler is going to change it anyway?
StringBuilder
for constant strings does not make sense. If I writeString s = "a" + "b" + "c";
compiler produces line that usingjavap -c
is shown like this:0: ldc #2 // String abc
. So it is smart and constant strings are "glued" into one. This means we can use + for code formatting purposes "for free" which is quite important. – Acth