4

Within Python I can use:

test = """My "cute" string"""

Where the double quotes get escaped. Is there a way that I can emulate this within Java without using escape slashes?

Maroun
  • 94,125
  • 30
  • 188
  • 241
Lucas Kauffman
  • 6,789
  • 15
  • 60
  • 86

5 Answers5

3

I don't see a reason not to escape ", but.. you can do:

System.out.println((char)34+"Some Text"+(char)34); //See ASCII table for more information

Output >> "Some Text"

Maroun
  • 94,125
  • 30
  • 188
  • 241
2

If you don't need an escape, you should use string concatenation such as:

test = '"' + "My " + '"' + "cute" + '"' + " string" + '"';

Or using StringBuffer to append " character if you want.

Another way to do that is using String.format:

test = String.format("%1$sMy %1$scute%1$s string%1$s", '"');

Which replaces %1$s by your give "quote" later.

Tu Tran
  • 1,957
  • 1
  • 27
  • 50
  • @SeanPatrickFloyd: Of course, I do not recommend to write a code like that. But I think that is a good way to have `"` character without escape. – Tu Tran Dec 02 '13 at 09:34
  • @TuTran, all pther approach instead of using `\\` will be error prone. Try using below answer's approach with OP's sample and the outcome complexity is same – Sage Dec 02 '13 at 09:36
2

Beginning with Java 13, Java now supports triple-quotes! See JEP 355 for details.

Sören
  • 1,803
  • 2
  • 16
  • 23
  • note that it was a Preview feature in 13; but official by 15: https://stackoverflow.com/a/59839267/1357094 – cellepo Aug 31 '23 at 19:51
1

You have to use \u0022.

String str= "\u0022 MyString \u0022";

But this is quite similar to escaping " by \

Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115
1

No, there is no sensible way of doing that in Java. Judging from the other answers, I'd say that escaping the quotes is the path of least pain.

It is possible in Groovy (which also runs on the Java VM), though, using either single quotes:

`'some "String"'`

or the so-called here documents:

""" Everything here can be "quoted"
/"""

But Java has no such mechanism.

Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588