5

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?

Zabuzard
  • 25,064
  • 8
  • 58
  • 82
SL5net
  • 2,282
  • 4
  • 28
  • 44
  • 1
    I don't think that answers the question, does it? The OP is apparently aware of the """ syntax and of text blocks, he's using it. The question is about escaping the quotes and/or the newline. You have to have a newline after `"""` (see https://openjdk.java.net/jeps/378), I don't think you should need to escape single quotes, though. – Petr Janeček Mar 08 '21 at 09:30
  • @PetrJaneček agreed, was going to vote to reopen but I see that's already been taken care of. – Federico klez Culloca Mar 08 '21 at 09:34
  • 2
    I reopened the question because it is **not** a duplicate. The question is not about how to create multi-line strings in Java, but about a detail of the text-blocks feature that came with Java-15. – Zabuzard Mar 08 '21 at 09:34
  • 2
    What you truly want are **raw strings**, not **text blocks**. Java doesnt have them (you can read the JEPs about text blocks and their history to see why). – Zabuzard Mar 08 '21 at 09:37

2 Answers2

8

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.

M A
  • 71,713
  • 13
  • 134
  • 174
7

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).

m.antkowicz
  • 13,268
  • 18
  • 37