Java Compiler是否包含String Constant Folding?

我发现Java支持原始类型的常量折叠 ,但是String呢?

如果我创建以下源代码

 out.write("" + "" + "" + "Easier to read if it is split into multiple lines" + "" + "" + ""); 

什么进入编译代码?

合并版? out.write("Easier to read if it is split into multiple lines");

或者效率较低的运行时级联版本? out.write(new StringBuilder("").append("").append("").append("Easier to read if it is split into multiple lines").append("").append("").append(""));

这是一个简单的测试:

 public static void main(final String[] args) { final String a = "1" + "2"; final String b = "12"; System.out.println(a == b); } 

输出:

 true 

所以,是的,编译器将弃用。

将使用组合版本
编译器会自动对其进行优化并将其放入字符串池中。

您可以通过编写此行轻松certificate此行为。

 System.out.println("abc" == "a" + ("b" + "c")); // Prints true 

这打印为true,意味着它是相同的对象 。 那是因为两件事:

  1. 编译器将"a" + ("b" + "c")"abc"
  2. 编译器将所有字符串文字放在字符串池中。 此行为称为字符串实习 。

它有效地转换为: out.write("Easier to read if it is split into multiple lines");