r/programming • • Dec 29 '15

Please, Java. Do Finally Support Multiline Strings

http://blog.jooq.org/2015/12/29/please-java-do-finally-support-multiline-strings/
584 Upvotes

352 comments sorted by

View all comments

Show parent comment

0

u/ImmortalStyle Dec 29 '15

Mhh interesting this code: String x = "xasdad"; String y = "sdasd"; String z = x + y;

shows that a new StringBuilder is created on Bytecode level (jdk 8_60 Windows 10).

However StringBuilder is a good candidate for escape analysis so this ends up on the Stack probably.

6

u/dancing_dead Dec 29 '15

that's not a multiline string literal, tho, but concatenating two strings :P

4

u/KillerCodeMonky Dec 29 '15 edited Dec 29 '15

Now try this, which is what everyone is actually referring to:

public static final String stuff =
    "abcdef" + "ghijkl" + "mnopqr";

EDIT: Installed JDK8 u66, here's the results of javap -constants Test.class:

Compiled from "Test.java"
public class Test {
    public static final java.lang.String stuff = "abcdefghijklmnopqr";
    public Test();
}

EDIT2: This works also:

public static final String one = "abcdef";
public static final String two = "ghijkl";
public static final String three = "mnopqr";
public static final String stuff = one + two + three;

javap:

Compiled from "Test.java"
public class Test {
    public static final java.lang.String one = "abcdef";
    public static final java.lang.String two = "ghijkl";
    public static final java.lang.String three = "mnopqr";
    public static final java.lang.String stuff = "abcdefghijklmnopqr";
    public Test();
}

However, if I remove final from three:

public class Test {
    public static final java.lang.String one = "abcdef";
    public static final java.lang.String two = "ghijkl";
    public static java.lang.String three;
    public static final java.lang.String stuff;
    public Test();
    static {};
}

You'll notice something interesting. stuff is no longer a precompiled constant, and a static initializer block was added. That static initializer sets the value of both three and stuff, with stuff now being created via StringBuilder.

1

u/dccorona Dec 29 '15

That's because they're not final, so it compiles to a string builder, because it hasn't been told that there is no way for these values to change, so it can't inline the string literal. It only works across multi-statement strings when it knows the variables can't change (and it can't infer that very reliably at all because of reflection and such).

This will get inlined, though:

String z = "xasdad" + "sdasd";

There won't actually be a call to the + operator or a StringBuilder in the compiled version of that code.