140

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?

Matthew
  • 28,056
  • 26
  • 104
  • 170
  • Related: http://stackoverflow.com/questions/2678483/simple-direct-heredoc-way-of-constructing-a-html-string-in-java – Michael Mrozek Jun 13 '10 at 22:49
  • [This answer](http://stackoverflow.com/a/121513/403455) shows how to paste multi-line escaped strings in Eclispe. – Jeff Axelrod Mar 09 '12 at 18:42
  • 3
    Update 2018: raw string literals for Java might be coming. [See my answer below](https://stackoverflow.com/a/48481601/6309) – VonC Jan 27 '18 at 23:24
  • import jackson ObjectMapper then `System.out.println(mapperObj.writeValueAsString(mapperObj.readValue(str, Object.class)));` – Kervvv Sep 26 '18 at 04:28
  • update Q4 2018: raw string literal are *not* coming just yet. See my [updated answer](https://stackoverflow.com/a/48481601/6309). – VonC Dec 15 '18 at 20:24
  • 1
    Coming back to this issue after away from java six years is irritating. – WestCoastProjects Jan 06 '20 at 04:51

8 Answers8

166

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.

benjismith
  • 16,559
  • 9
  • 57
  • 80
  • wouldn't you need to use replaceAll? – Landon Kuhn Jun 15 '12 at 03:58
  • 15
    @landon9720 No, .replace replaces all occurrences of a character/character sequence with another character/character sequence. .replaceAll uses regex. – abelito Jul 16 '12 at 20:54
  • Out of curiosity do you know if the java compiler would simplify this upon compiling? – ug_ Aug 17 '14 at 00:23
  • 2
    No, I don't think the compiler would simplify this. But it doesn't really matter. It's a very inexpensive call, and if I only do this for static final strings, the cost will only be incurred once, upon classloading. That's a price I'm usually willing to pay for nicer looking code :) – benjismith Apr 19 '15 at 23:29
  • 3
    Then what about "\" in myString? – Anderson Feb 21 '17 at 11:51
  • This is such a simple and yet fancy thing – Jorge.V Jun 06 '19 at 09:06
79

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

sax
  • 808
  • 1
  • 12
  • 25
Jack
  • 131,802
  • 30
  • 241
  • 343
17

Since Java 15¹ there is new feature called Text Blocks. It looks similar to what you mentioned is available in Python:

String text = """
              {
                 "property": "value",
                 "otherProperty": 12
              }
              """;

More details with examples can be found here: https://openjdk.java.net/jeps/378 JEP 378: Text Blocks


¹ Previewed in Java 13 and 14.

StackzOfZtuff
  • 2,534
  • 1
  • 28
  • 25
Mateusz Marchel
  • 772
  • 4
  • 14
14

Update Dec. 2018 (12 months later):

Raw string literals (which are on the amber list) won't make it to JDK 12.
See the criticisms here.


There might be in a future version of Java (10 or more).

See JEPS 8196004 from January 2018: ("JEP" is the "JDK Enhancement Program")

JEP draft: Raw String Literals

Add a new kind of literal, a raw string literal, to the Java programming language.
Like the traditional string literal, a raw string literal produces a String, but does not interpret string escapes and can span multiple lines of source code.

So instead of:

Runtime.getRuntime().exec("\"C:\\Program Files\\foo\" bar");
String html = "<html>\n"
              "    <body>\n" +
              "         <p>Hello World.</p>\n" +
              "    </body>\n" +
              "</html>\n";
System.out.println("this".matches("\\w\\w\\w\\w"));

You would be able to type:

Runtime.getRuntime().exec(`"C:\Program Files\foo" bar"`);
    
String html = `<html>
                   <body>
                       <p>Hello World.</p>
                   </body>
               </html>
              `;

System.out.println("this".matches(`\w\w\w\w`));

Neat!

But it is still just a draft: it will need to posted, submitted, be a candidate, and funded, before being completed and making it into the next JDK.

Community
  • 1
  • 1
VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
5

Simple answer: No.

For longer strings that must be escaped, I usually read them from some external resource.

Chris Lercher
  • 37,264
  • 20
  • 99
  • 131
3

you can also use StringEscapeUtils from apache commons

UPDATE: If someone is interested in some examples here is a useful link : https://dzone.com/articles/commons-lang-3-improved-and-powerful-StringEscapeUtils

Razzle
  • 479
  • 4
  • 11
Doua Beri
  • 10,612
  • 18
  • 89
  • 138
  • 5
    Could you please add an example possibly based on the question illustrating how to it for this problem? – Bengt Jun 14 '13 at 17:13
  • 9
    [It is considered suboptimal to only reference another resource that might answer the question.](http://meta.stackexchange.com/questions/8231/are-answers-that-just-contain-links-elsewhere-really-good-answers) Please consider summarizing the linked page with an example matching the question. – Bengt Jun 23 '13 at 19:55
  • I took a look and don't think either really answers the question. The inputs to the static methods are `String`s, so no way to have a nicely formatted value in your code. Presumably you could use these methods to read from a file into a `String`, but I don't think that's the question here. – Tom Harrison Jan 08 '17 at 23:41
  • The linked class (org.apache.commons.lang3.StringEscapeUtils) has been deprecated and replaced with [org.apache.commons.text.StringEscapeUtils](https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/StringEscapeUtils.html) – jcarter Oct 24 '19 at 14:43
-1

You could use left and/or right quotes if you don't mind the difference, they look pretty similar:

"These “double quotes” don't need nor want to be escaped"
h4nek
  • 86
  • 2
  • 8
-5

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).

Adam Jensen
  • 541
  • 1
  • 10
  • 25
  • 1
    I think because char is the primitive variable type for String <- Your assumption is incorrect. For that matter, it will also work with a different type, like an int, like so: String x = "Some text" + 33 + "More text"; – Najeeb Sep 02 '16 at 11:54