7

I know that it is possible to write double quotes in Java strings by putting \ symbol before them. But if double quotes are used a lot in a string, is there a way to mark the string once, so there won't be a need to write the \ symbol before each? (just like in C#, it is possible to put the @ symbol before the string) Example:

String quotes = @"""""""""""""""""""";

instead of

String quotes = "\"\"\"\"\"\"\"\"\"\"\"";
Victor2748
  • 4,149
  • 13
  • 52
  • 89
  • similar question: http://stackoverflow.com/questions/10806973/working-with-long-strings-heredocs-in-java-the-readable-approach – Felk Oct 17 '14 at 01:24
  • 1
    Note (Jan. 2018), raw string literals might be coming for Java (JDK 10 or more): see [In Java, is there a way to write a string literal without having to escape quotes?](https://stackoverflow.com/a/48481601/6309). – VonC Jan 27 '18 at 23:25
  • @VonC Lets hope. Slowly but surely java is making progress :) – Victor2748 Jan 28 '18 at 22:41

3 Answers3

8

You can't. But if you are too lazy to escape each of the double quotes, there are some trick that can do that. For example:

String quotes = "....................".replace(".","\"");
System.out.println(quotes);

output: """"""""""""""""""""

DnR
  • 3,487
  • 3
  • 23
  • 31
5

No, there is no such way to write a String literal with unescaped quotes.

You can write the text externally and load it at runtime.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
1

There is no way to escape all subsequent double quotes in code (that I know of). But, I recommend against hard-coding String literals. Instead, I suggest you use a ResourceBundle (or even Properties). One benefit being you don't have to escape String(s) you read in that way.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249