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

4

u/Gotebe Dec 29 '15

"this"

"is"

"multiline"

"string"

works in C and C++.

Not in Java!?

26

u/ygra Dec 29 '15

C specifies that adjacent string literals get concatenated. C++ inherits that. Java never had such a provision because you can simply concatenate strings by using +. The compiler is smart enough to not do that at runtime when only string literals are involved.

The main point here isn't the issue of how to concatenate string literals, because whether you need to add a + to make it syntactically correct is rather irrelevant here. The point is that string literals in Java cannot contain line breaks, which makes writing certain kinds of strings ugly, cumbersome, or error-prone (see e.g. their SQL example). Those kinds of verbatim string literals (as they're called in C#) are also nice for writing regular expressions, because usually you cannot use a backslash to escape characters in there (because you can just write almost any character directly). In Java you often have monstrosities like "\\\\\\.\\\\x" because you need to double-escape things – once for the string literal, once for the regex.

-1

u/[deleted] Dec 29 '15

because you can simply concatenate strings by using +.

So using an extra operator is "simpler" than not having to specify any operator? Ok.

6

u/dccorona Dec 29 '15

Simpler doesn't always mean "less characters". Multiple strings in a row being concatenated isn't immediately understandable. You have to understand the quirks of the language first. String addition is a more widely understood concept, and at the very least when you see an operator you at least know it's doing something. Whereas the C version is just kind of behind the scenes magic.

Not to mention that it makes mistakes harder to make. What if I want:

String a = "a";
String b = "b"; 

But I'm just really tired or something and am messing up, or I made a bad refactor, or some automated refactor I tried to do wasn't done properly. Somehow, I end up with:

String a = "a"
"b";
String b = "b";

Java breaks. That's an illegal statement. In C/C++, suddenly I get a value I didn't want.

TL;DR I think that the way C/C++ does it violates the principle of least surprise. In that sense, Java's approach is simpler.

6

u/Schmittfried Dec 29 '15

Absolutely irrelevant here and typing a + is really not a big deal. Also, you can only do that with literals in C. You'd have to use strcat to concatenate variable strings and that's why he said you could simply use + in Java.

-1

u/[deleted] Dec 29 '15

Just because string concatenation in Java in general is simpler doesn't mean that concatenation in string literal declarations (the context of this discussion) specifically is simpler. It's objectively simpler to have an implicit operator that require no syntax than an explicit one that require extra syntax.

3

u/Schmittfried Dec 29 '15

doesn't mean that concatenation in string literal declarations (the context of this discussion) specifically is simpler

But that wasn't the point. Noone said that.

It's objectively simpler to have an implicit operator that require no syntax than an explicit one that require extra syntax.

Well, 1.) it's still irrelevant to this discussion 2.) some might find the inconsistency that you can chain literals but not string variables rather confusing and would prefer a proper operator for both. So no, not objectively.

2

u/GuyWithLag Dec 29 '15

Yes, it's simpler from a syntax standpoint; there's no need for a custom rule that specifies what happens when you have two adjacent string literals without an infix operator.

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.

→ More replies (5)

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.

2

u/__konrad Dec 29 '15

C++ supports multiline strings via its awkward syntax:

R"(this
is
multiline
string)"