javajava-text-blocks

Text blocks in a single line


Is it possibly to use Javas text blocks feature (Java 15) but only write a single line?

It seems that I am forced to write multiple lines.


For example, I want write this in one line to avoid escaping the " in it

String text = """<a href="https://sparkjava.com">https://sparkjava.com/</a>""";

but it does not compile and I have to write

String text = """
    <a href="https://sparkjava.com">https://sparkjava.com/</a>""";

instead.

Am I overlooking something?


Solution

  • No it's not possible as text blocks require a newline as part of the opening delimiter:

    The opening delimiter is a sequence that starts with three double quote characters ("""), continues with zero or more space, tab, and form feed characters, and concludes with a line terminator.

    So you can't have a text block with only a single line.