Does Java Compiler include String Constant Folding?

南笙酒味 提交于 2019-11-28 02:01:53
Reverend Gonzo

Here's an easy test:

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

    System.out.println(a == b);
}

Output:

true

So, yes, the compiler will fold.

The combined version will be used.
The compiler optimises this automatically and puts it in the String Pool.

You can prove this behaviour easily by writing this line.

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

That this prints true, means that it are the same objects. That is because of two things:

  1. The compiler optimised "a" + ("b" + "c") to "abc".
  2. The compiler puts all string literals in the string pool. This behaviour is called String Interning.

It effectively translates to: out.write("<markup><nested>Easier to read if it is split into multiple lines</nested></markup>");

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!