javascalajava-text-blocks

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!


Solution

  • 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:

    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.