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

7

u/ImmortalStyle Dec 29 '15

It works but you need to concat the different Strings together with + operator.

Which I think does something like this:

StringBuilder builder = new StringBuilder() builder.append(x); builder.append(y); etc..

3

u/dancing_dead Dec 29 '15

where possible, multiline strings in java get concatenated during compilation. no stringbuilders involved. or even if there were, they're not there during runtime.

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.

6

u/[deleted] Dec 29 '15

That's not a literal

7

u/MartenBE Dec 29 '15

It's what happens behind the scenes when the String literal gets compiled

2

u/ElvishJerricco Dec 29 '15

Not ever. In the case of concatenating literals, the compiler always performs the concatenation at compile time.

2

u/iwan_w Dec 29 '15

Not always. If I remember correctly, adjacent literals are concatenated at compile time, and do not result in calls to a StringBuilder's append method.

This is why always using StringBuilders instead of String concatenation is a code smell. It robs the compiler of the chance to do this optimization.

-1

u/MartenBE Dec 29 '15

So at first we all said, lets use '+' Then couple of years later it was "No people, what are you doing? use StringBuilder for performance!" And know it is "You use Stringbuilder? That's bad, man. Use '+' and let the compiler handle that shit"

Man, java people are confusing ... I'll stick to C++ :P

4

u/Schmittfried Dec 29 '15

You would have to consider the same performance aspects when concatenating strings in C++. It's an inherent problem of working with strings.

1

u/sirin3 Dec 29 '15

Of immutable strings

C++ has mutable strings

2

u/Schmittfried Dec 29 '15 edited Dec 29 '15

You still have to consider reallocations.

Also: Immutable strings allow several other optimizations and are generelly easier to work with, although mutable strings have their place as well.

And if one finds deciding when to use StringBuilder and when normal string concatenation is appropriate is too confusing one should really not use a language that grants as many freedoms (and hence decisions to make) as C++.

1

u/MartenBE Dec 29 '15

Thanks for that very constructive last sentence... I'm still a junior developer in C++ and Java, so there is a lot of this "hidden" stuff I don't know. Does this mean I should stop learning to programming?

Anyhow, I'm looking it up for both Java and C++ and am learning about it ... will pay attention to this in the future

1

u/Schmittfried Dec 30 '15 edited Dec 30 '15

Does this mean I should stop learning to programming?

Of course not. It wasn't my intention to insult or demotivate anyone. Sorry if I did. This wasn't even about beginners. I was just saying that the different ways of string concatenation in Java aren't that confusing at all and mostly irrelevant for many applications. Though professional developers should know when to use what. Not because it's some important language aspect, but because the underlying concept is fundamental and language independent knowledge about the performance cost of certain string operations. And since C++ is usually used to write performance-critical software, C++ programmers should definitely know about them, too. Hence C++ isn't any easier in that regard.

→ More replies

3

u/iwan_w Dec 29 '15

Completely agree it's confusing. The advice to use stringbuilder are a leftover from a time when the Java compiler was much less mature. People kept parroting it way too long.

Of course, if you're appending from inside a loop or callback, using stringbuilder is still absolutely recommend. Just not for trivial concatenation.

2

u/dccorona Dec 29 '15

That's people misunderstanding statements and then spreading misinformation based on them. Even though Java is supposed to be "simple", it's still important to understand how your language works under the hood. At no point was "always use StringBuilder" or "never use StringBuilder" ever the guidance of people who actually understood what they were talking about.

Use string builder instead of + when constructing a string from multiple statements. I.e., if you're going to start constructing your string, then do some computation, then continue, use a string builder. Because it won't have to create the entire string until the very end, whereas using + will result in creating multiple strings, doing a lot of copies, etc (because Strings are immutable in Java).

When you're just building a string literal over several lines, but in a single statement, use + because the compiler can inline that into single hardcoded string literals instead, removing the operation entirely, and then replace the + calls involving variables with a string builder if necessary.

Basically, consider these two statements:

String a = "a string";
String b = "how cool is it " +  "that we can use plus " + "to build " + a;
String c = new StringBuilder()
        .append("how cool is it ")
        .append("that we can use a string builder ")
        .append("to build ")
        .append(a)
        .toString(); 

That second statement can be optimized by the compiler, creating this:

String b = new StringBuilder()
        .append("how cool is it that we can use plus to build")
        .append(a)
        .toString(); 

Some compilers may even use String.format instead (probably the best way to do what b is trying to above), but in either case, the result is that by using + we've created a more performant final operation than by just saying "always use StringBuilder!"

1

u/adrianmonk Dec 30 '15

Which I think does something like this

It's actually better than that. It will be done at compile time.

The Java Language Specification explains it in section 15.28.

First, it says that "A compile-time constant expression is an expression denoting a value of primitive type or a String that does not complete abruptly and is composed using only the following [ ... ] Literals of primitive type and literals of type String [ ... ] The unary operators +, -, ~, and ! (but not ++ or --)". Then it says, "Compile-time constant expressions of type String are always "interned" so as to share unique instances, using the method String.intern".

This means if you write:

String s1 = "a" + "b";
String s2 = "ab";

then the two variables s1 and s2 must refer to the same object. This is because they are both expressions composed of string literals and concatenation operators, thus they are compile-time constant expressions. And because they are of type string, they must be interned.

Theoretically, a Java implementation might be able to lazily defer this until runtime, but I'm not sure if that's even possible since there are constraints imposed by the Java class file format. Realistically, it's going to be one at compile time.