Just came across a new feature in Java 15 i.e. "TEXT BLOCKS". I can assume that a variable can be added inside a text block by concatenating with a "+" operator as below:
String html = """
<html>
<body>
<p>Hello, """+strA+"""</p>
</body>
</html>
""";
But are they providing any way so that we can add variables the way which is becoming popular among many other languages as below:
String html = """
<html>
<body>
<p>Hello, ${strA}</p>
</body>
</html>
""";
This question might sound silly but it may be useful in certain scenario.
Since Java 15, text blocks are available as a standard feature. With Java 13 and 14, we needed to enable it as a preview feature. Text blocks start with a “”” (three double-quote marks) followed by optional whitespaces and a newline. The most simple example looks like this: Note that the result type of a text block is still a String.
The instance produced from a text block is of type java.lang.String with the same characteristics as a traditional double quoted string. This includes object representation and interning into string pool. We can use text blocks to pass as method arguments of type String.
Only use a text block when it improves the clarity of the code, particularly with multi-line strings. If a string fits in the usecase, always prefer to use strings. They are better for application performance. To maintain the desired indentation, always use the position of closing triple quotes relative to the position of the last line on content.
The instance produced from a text block is of type java.lang.String with the same characteristics as a traditional double quoted string. This includes object representation and interning into string pool.
Java 15 does not support interpolation directly within text blocks nor plain string literals.
The solution in Java 15 is to use String.formatted()
method:
String html = """
<html>
<body>
<p>Hello, %s</p>
</body>
</html>
""".formatted(strA);
From the spec for text blocks:
Text blocks do not directly support string interpolation. Interpolation may be considered in a future JEP.
"String interpolation" meaning
evaluating a string literal containing one or more placeholders, yielding a result in which the placeholders are replaced with their corresponding values
from Wikipedia
As stated above, maybe we'll get it in the future. Though it is difficult to say how they could possibly implement that without breaking backwards compatibility -- what happens if my string contains ${}
, for example? The Java language designers rarely add anything that is likely to break backwards compatibility.
It seems to me that they would be better off either supporting it immediately, or never.
Maybe it would be possible with a new kind of text block. Rather than the delimiter being """
, they could use '''
to denote a parameterized text block, for example.
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