5

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 goes into the compiled code?

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

Or the less efficient run-time concatenation version? out.write(new StringBuilder("").append("<markup>").append("<nested>").append("Easier to read if it is split into multiple lines").append("</nested>").append("</markup>").append(""));

StayOnTarget
  • 11,743
  • 10
  • 52
  • 81
700 Software
  • 85,281
  • 83
  • 234
  • 341

3 Answers3

16

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.

Xion
  • 22,400
  • 10
  • 55
  • 79
Reverend Gonzo
  • 39,701
  • 6
  • 59
  • 77
2

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.
Martijn Courteaux
  • 67,591
  • 47
  • 198
  • 287
-1

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

user1071777
  • 1,307
  • 1
  • 15
  • 23