Since Java 15
or since Java 13 preview feature. REF: https://openjdk.java.net/jeps/355
It doesn't work precisely in Scala way. The opening triple quotes must be followed by a new line.
var expr = """
This is a 1-line "string" with "quotes" and no leading spaces in it! """;
The position of the closing triple quotes matters. It defines the indent size. For example, for having 2 spaces indent, you position your closing """
as follows:
String sql = """
SELECT emp_id, last_name
FROM postgres.employee
WHERE city = 'INDIANAPOLIS'
ORDER BY emp_id, last_name;
""";
this would result in 4 lines of text:
SELECT emp_id, last_name
FROM postgres.employee
WHERE city = 'INDIANAPOLIS'
ORDER BY emp_id, last_name;
Escaping:
Tripple quotes escaping is intuitive:
String txt = """
A text block with three quotes \""" inside.""";
\
(backslash) is still a special symbol. You have to escape it by doubling \\
:
String txt = """
A text block with a single blackslash \\ in it.""";
Trailing spaces
Java compiler ignores any ending spaces.
WORKAROUND: add \s
to the end of the line. (Baeldung example)
Windows \r\n
line terminators
No matter if you compile in MacOs or Windows, the string constant will always use \n
and only \n
WORKAROUND: add \r
to the end of the line. (Baeldung example)
Concatenating 2 lines
Since Java 14 preview, you may continue the same line below, if the previous one ended with a single backslash:
var oneLine = """
This is one \
line of text!""";
Result:
This is one line of text!
Enjoy ;)
You can play with the output right away in an online Java 17+ compiler: https://www.jdoodle.com/online-java-compiler/
NOTE: If using in Java 13(14), the feature was preview, there. So you could not use it in Java 13(14), unless you set the --enable-preview TextBlock
key.