In Scala you can do something like this:
val expr = """ This is a "string" with "quotes" in it! """
Is there something like this in Java? I abhor using "\""
to represent strings with quotes in them. Especially when composing key/value pairs in JSON. Disgusting!
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.
Text Block SyntaxText blocks comprise multiple lines of text and uses three double-quote characters (“””) as its opening and closing delimiter. The opening three double-quote characters are always followed by a line terminator.
Scala has triple quoted strings """String\nString""" to use special characters in the string without escaping. Scala 2.10 also added raw"String\nString" for the same purpose.
Double quotes can be inserted using the following ways in java as listed below: Using Escape Sequence character. Using char. Using Unicode Characters.
There is no good alternative to using \"
to include double-quotes in your string literal.
There are bad alternatives:
\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 a String
literal, so this does NOT work.'"'
, e.g. "This is a " + '"' + "string"
. This will work, but it seems to be even uglier and less readable than just using \"
.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."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.
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