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
  • 161,005
  • 26
  • 328
  • 327
Alok
  • 1,264
  • 2
  • 15
  • 42

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
  • 191,680
  • 20
  • 149
  • 239
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,335,956
  • 823
  • 8,931
  • 9,049