Text blocks in a single line

2.2k views Asked by At

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?

2

There are 2 answers

1
M A On BEST ANSWER

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.

0
m.antkowicz On

No - it is not possible because there is mandatory new line after """ operator

Due to the documentation

A text block begins with three double-quote characters followed by a line terminator. You can't put a text block on a single line, nor can the contents of the text block follow the three opening double-quotes without an intervening line terminator. The reason for this is that text blocks are primarily designed to support multi-line strings, and requiring the initial line terminator simplifies the indentation handling rules (see the section below, Incidental White Space).