Does the Java Compiler String Constant Folding?

I found out that Java supports constant folding of primitive types , but what about Strings?

Example

If I create the following source code

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

What is included in the compiled code?

The combined version? out.write("<markup><nested>Easier to read if it is split into multiple lines</nested></markup>");

Or a less efficient version of concatenation at runtime? out.write(new StringBuilder("").append("<markup>").append("<nested>").append("Easier to read if it is split into multiple lines").append("</nested>").append("</markup>").append(""));

+5
source share
3 answers

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);
}

Conclusion:

true

So yes, the compiler will discard the cards.

+14
source

The combined version will be used.
The compiler optimizes this automatically and places it in the string pool.

, .

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

true, , . - :

+1

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

-1

All Articles