Triple quotes in Java like Scala
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.""";
NOTE: This feature is preview, so you cannot use it in Java 13, unless you set the --enable-preview TextBlock
key.
UPDATE: The feature went to the second preview (JEP 368) with Java 14.
Will be waiting for Java 15.
There is no good alternative to using \"
to include double-quotes in your string literal.
There are bad alternatives:
- Use
\u0022
, the Unicode escape for a double-quote character. The compiler treats a Unicode escape as if that character was typed. It's treated as a double-quote character in the source code, ending/beginning aString
literal, so this does NOT work. - Concatenate the character
'"'
, e.g."This is a " + '"' + "string"
. This will work, but it seems to be even uglier and less readable than just using\"
. - Concatenate the
char
34 to represent the double-quote character, e.g."This is a " + (char) 34 + "string"
. This will work, but it's even less obvious that you're attempting to place a double-quote character in your string. - Copy and paste Word's "smart quotes", e.g.
"This is a “string” with “quotes” in it!"
. These aren't the same characters (Unicode U+201C and U+201D); they have different appearances, but they'll work.
I suppose to hide the "disgusting"-ness, you could hide it behind a constant.
public static final String DOUBLE_QUOTE = "\"";
Then you could use:
String expr = " This is a " + DOUBLE_QUOTE + "string" + DOUBLE_QUOTE + ...;
It's more readable than other options, but it's still not very readable, and it's still ugly.
There is no """
mechanism in Java, so using the escape \"
, is the best option. It's the most readable, and it's the least ugly.