Skip to content
Advertisement

In Java, is there a way to write a string literal without having to escape quotes?

Say you have a String literal with a lot of quotation marks inside it. You could escape them all, but it’s a pain, and difficult to read.

In some languages, you can just do this:

foo = '"Hello, World"';

In Java, however, '' is used for chars, so you can’t use it for Strings this way. Some languages have syntax to work around this. For example, in python, you can do this:

"""A pretty "convenient" string"""

Does Java have anything similar?

Advertisement

Answer

The answer is no, and the proof resides in the Java Language Specification:

  StringLiteral:
   "StringCharacters"

  StringCharacters:
   StringCharacter
   | StringCharacters StringCharacter

  StringCharacter:
   InputCharacter but not " or 
   | EscapeSequence

As you can see a StringLiteral can just be bound by " and cannot contain special character without escapes..

A side note: you can embed Groovy inside your project, this will extend the syntax of Java allowing you to use '''multi line string ''', ' "string with single quotes" ' and also "string with ${variable}".

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement