Java compiler replaces StringBuilder with concatenation

Here are some simple java code:

String s = new StringBuilder().append("a").append("b").append("c").toString();

I compiled it with JRE 1.6, and I observed the following in the decompiled class file:

String s = "a" + "b" + "c";

I have the following questions:

>Why did the compiler choose "instead of StringBuilder? > Do we have any formal Java specifications to justify this behavior? > Does it really make sense to use StringBuilder in this case, and do we know that the compiler will change it?

Solution

Conversely For string is implemented behind the scenes using StringBuilder (or StringBuffer) (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).

Therefore, once the compilation is complete, your two code fragments are difficult to distinguish The decompiler must guess the original form

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>