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

114,829

Solution 1

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 ').

Solution 2

It's best practice only to escape the quotes when you need to - if you can get away without escaping it, then do!

The only times you should need to escape are when trying to put " inside a string, or ' in a character:

String quotes = "He said \"Hello, World!\"";
char quote = '\'';
Share:
114,829
Naetmul
Author by

Naetmul

Updated on August 07, 2021

Comments

  • Naetmul
    Naetmul over 2 years

    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."

  • Stephen C
    Stephen C almost 11 years
    Umm ... where does it say that this is "best practice"? Or are you just relabelling your personal preferences as "best practice"?
  • Mishax
    Mishax over 8 years
    but you can and it is legal, is what you're saying, right?
  • Zaid Khan
    Zaid Khan over 7 years
    @Mishax it's quite obvious. The only use of the escape character is to tell the compiler to not treat the character('/") as the closing character.
  • Mishax
    Mishax over 7 years
    @Bateman I disagree with your statement - the escape character can be used in a String literal with \n to indicate a newline or a \t for a tab. My hint to Cory Kendall was that his answer did not use formal terms like "legal but optional" which would have been more precise.
  • acid_crucifix
    acid_crucifix over 4 years
    for example, i have found it useful when im doing search and replace across a large file. today i want to replace \" -> \' tomorrow i may want to do the opposite. but ' -> \" may end up matching cases i do not want to replace
  • Gili
    Gili almost 2 years
    @StephenC Readability is a best practice :) I'll leave it at that.
  • Stephen C
    Stephen C almost 2 years
    @Gili - You need to read this: No Best Practices - It starts: "Dear Reader, I would like you to give up, henceforth, the idea of “best practice.” Thank you."