The Java 13 multi line text block facility with """
delimiters is becoming well known.
However I have a recurring need where I need entire paragraphs without the embedded newlines.
In other words, the following code snippet:
String paragraph =
"""
aaaa bbbb cccc
dddd eeee ffff
gggg hhhh iiii
""";
System.out.println(paragraph);
produces the following, as you'd expect:
aaaa bbbb cccc
dddd eeee ffff
gggg hhhh iiii
...which is usually tremendously useful. However in my case, for particularly large paragraphs I need it to produce this:
aaaa bbbb cccc dddd eeee ffff gggg hhhh iiii
(....and deal with text flow later.)
Is there a way to establish a "no-newline" parameter for the triple-quote feature?
The opening triple quotes must be followed by a new line. var expr = """ This is a 1-line "string" with "quotes" and no leading spaces in it! """; The position of the closing triple quotes matters.
Text blocks start with a “”” (three double-quote marks) followed by optional whitespaces and a newline. The most simple example looks like this: String example = """ Example text"""; Note that the result type of a text block is still a String.
If you want your string to span multiple lines, you have to concatenate multiple strings: String myString = "This is my string" + " which I want to be " + "on multiple lines."; It gets worse though. If you want your string to actually contain new lines, you need to insert \n after each line.
A text block's principalis munus is to provide clarity by way of minimizing the Java syntax required to render a string that spans multiple lines. In earlier releases of the JDK, embedding multi-line code snippets required a tangled mess of explicit line terminators, string concatenations, and delimiters.
The designers of this feature realized this requirement as well (see 'New escape sequences' in JEP368). So, with the latest early access build for JDK 14 you can use a trailing \
to escape the new line at the end of a line:
public class Main {
public static void main(String[] args) {
String paragraph =
"""
aaaa bbbb cccc \
dddd eeee ffff \
gggg hhhh iiii \
""";
System.out.println(paragraph);
}
}
Prints:
aaaa bbbb cccc dddd eeee ffff gggg hhhh iiii
You can use String.lines
introduced since Java-11 as:
String output = paragraph.lines().collect(Collectors.joining());
A complimentary and for what's worth it, here is a screenshot from JShell execution of the two different blocks of code:
Indeed, finding a good answer in Java 13 is not easy (maybe even impossible) but I think Jorn Vernee addressed the concern gracefully in his reply (new escape sequences in Java 14 provide an acceptable solution).
To expand on several listed concerns:
(Let's not forget that text blocks are in 'second preview' mode).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With