Coming from Perl, I sure am missing the "here-document" means of creating a multi-line string in source code:
$string = <<"EOF" # create a three-line string
text
text
text
EOF
In Java, I have to have cumbersome quotes and plus signs on every line as I concatenate my multiline string from scratch.
What are some better alternatives? Define my string in a properties file?
Edit: Two answers say StringBuilder.append() is preferable to the plus notation. Could anyone elaborate as to why they think so? It doesn't look more preferable to me at all. I'm looking for a way around the fact that multiline strings are not a first-class language construct, which means I definitely don't want to replace a first-class language construct (string concatenation with plus) with method calls.
Edit: To clarify my question further, I'm not concerned about performance at all. I'm concerned about maintainability and design issues.
Best Answer
It sounds like you want to do a multiline literal, which does not exist in Java.
Your best alternative is going to be strings that are just
+
'd together. Some other options people have mentioned (StringBuilder, String.format, String.join) would only be preferable if you started with an array of strings.Consider this:
Versus
StringBuilder
:Versus
String.format()
:Versus Java8
String.join()
:If you want the newline for your particular system, you either need to use
System.lineSeparator()
, or you can use%n
inString.format
.Another option is to put the resource in a text file, and just read the contents of that file. This would be preferable for very large strings to avoid unnecessarily bloating your class files.