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!
Note: This answer was written prior to Java 15, which introduced the triple-quote text block feature. Please see @epox's answer for how to use this feature.
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 aStringliteral, 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\".char34 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.
Then you could use:
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.