0

I need to use a string something like this

String x = "return "My name is X" ";

We can see the issue is first and second quotes wll be treated as a String in itself , but actually first and last quote should form 1 string , while 2nd and 3rd quotes should form another string inside that.

Any solution for this?

tim_yates
  • 167,322
  • 27
  • 342
  • 338
Alok
  • 1,374
  • 3
  • 18
  • 44

2 Answers2

3

Escape the quotes or use String concatenation like

String x = "return \"My name is X\" ";

or

String x = "return " + '"' + "My name is X" + '"' + " ";
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
2

You just need to escape the double-quote within the string literal:

String x = "return \"My name is X\" ";

There are other characters which can be escaped like this too - for example:

String tab = "before\tafter";

(That's "before", then a tab, then "after".)

See the JLS section 3.10.6 for all escape sequences.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194