in java is there a way to write a string literal without having to escape quote

in java is there a way to write a string literal without having to escape quote  using -'java,string,escaping'

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?

asked Sep 22, 2015 by girisha
0 votes

4 Answers

0 votes

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


   | StringCharacters 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}".

answered Sep 22, 2015 by deepak gupta
0 votes

you can also use StringEscapeUtils from apache commons

UPDATE: If someone is interested in some examples here is a useful link :

answered Sep 22, 2015 by amit_cmps
0 votes

No, and I've always been annoyed by the lack of different string-literal syntaxes in Java.

Here's a trick I've used from time to time:

String myString = "using `backticks` instead of quotes".replace('`', '"');

I mainly only do something like that for a static field. Since it's static the string-replace code gets called once, upon initialization of the class. So the runtime performance penalty is practically nonexistent, and it makes the code considerably more legible.

answered Sep 22, 2015 by atulpariharmca
0 votes

The following seems to work for me:

String x = "Some Text" + '"' + "More Text" + '"' + "Even More Text";

I think because char is the primitive variable type for String, Strings and chars can be combined (at least the eclipse compiler doesn't seem to complain).

answered Sep 22, 2015 by gauravsinghal83