Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Triple quotes in Java like Scala

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!

like image 621
HiChews123 Avatar asked Feb 06 '15 00:02

HiChews123


People also ask

How do you use triple quotes in Java?

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.

What does triple quotes mean in Java?

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.

What is triple quotes in Scala?

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.

Can you use double quotes in Java?

Double quotes can be inserted using the following ways in java as listed below: Using Escape Sequence character. Using char. Using Unicode Characters.


1 Answers

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 a String 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.

like image 99
rgettman Avatar answered Oct 06 '22 01:10

rgettman