Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Compiler replacing StringBuilder with + concatenation

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:

  1. Why does the compiler choose '+' over StringBuilder?
  2. Do we have any official Java specification that justifies this behavior?
  3. Does it really make sense to use StringBuilder in such cases, where we know compiler is going to change it anyway?
like image 551
Gaurav Avatar asked Nov 30 '22 01:11

Gaurav


1 Answers

It's the other way round. + for String is implemented using StringBuilder (or StringBuffer) behind the scenes (see http://docs.oracle.com/javase/7/docs/api/java/lang/String.html or http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.18.1).

Thus, once they're compiled, your two code snippets are indistinguishable. The decompiler has to make a guess at the original form.

like image 114
Oliver Charlesworth Avatar answered Dec 04 '22 15:12

Oliver Charlesworth