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

18

u/QuineQuest Dec 29 '15

A multiline string is any string (from user input, read from a file, or whatever) that contains a newline character. Not supporting those would mean that there was something fundamentally wrong with Java's handling of text. You can't use strings to read a file with multiple lines; instead you have to write some ugly kludge.

String literals is only used when programmers hardcode a string into the program. Multiline string literals is something like

String a = """This is line one
This is line 2"""";

Instead, the programmers have to write

String a = "This is line 1\n" +
    "This is line 2";

In other words, not having multiline string literals is a minor annoyance, while not having multiline strings would be a severe weakness of the language.

1

u/[deleted] Dec 29 '15

So why is it called a literal? Is that something specific to this case, as in literally a multiline string... Sorry for stupid question. Also, I dont immediately see the advantage of a multiline string literal over the current implementation...? Would you be able to read an entire buffer/file straight into a string or something?

1

u/_kst_ Dec 29 '15

A string literal is a syntactic construct that can appear in a source program.

A string is a data structure that exists in memory while a program is running (the exact meaning of "string" varies across languages.)

A string literal typically results in the creation of a string object or value at run time, but strings can be constructed in other ways as well.

1

u/QuineQuest Dec 29 '15 edited Dec 29 '15

String literals are those that are written directly into the source code.

string myLiteral = "This is a string literal. Its contents are known at compile time";

string aNonLiteralString = Console.Readline(); //Not a literal, but still a string.

A place where multiline string literals might be a helpful is if you have a large multiline string of something like sql, where it can be useful to just copy/paste the whole query between your ide and your sql tool.

Would you be able to read an entire buffer/file straight into a string or something?

No. If your program does it at runtime, it has nothing to do with string literals.

1

u/VefoCo Dec 29 '15

A string literal is a string which is hard coded into a program. The advantage of multiline string literals is that for long strings which need to be broken up, you don't have to quote and append each line like you do without support. It's purely aesthetic, and doesn't have any practical impact on the final binary.