Search code examples
javastringdouble-quotes

Java 13 Triple-quote Text Block *WITHOUT* newlines


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?


Solution

  • 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