In Java, should I escape a single quotation mark (') in String (double quoted)?

Naetmul picture Naetmul · May 21, 2013 · Viewed 99.7k times · Source

In Java, \' denotes a single quotation mark (single quote) character, and \" denotes a double quotation mark (double quote) character.

So, String s = "I\'m a human."; works well.

However, String s = "I'm a human." does not make any compile errors, either.

Likewise, char c = '\"'; works, but char c = '"'; also works.

In Java, which is better to use? In HTML or CSS, things like style="font-family:'Arial Unicode MS';" are more often (and for such tags, I think it's the only way to use quotation marks), but in Java, I usually saw people use escape characters like "I\'m a human."

Answer

Cory Kendall picture Cory Kendall · May 21, 2013

You don't need to escape the ' character in a String (wrapped in "), and you don't have to escape a " character in a char (wrapped in ').