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."
Using Single-Quoted strings: While using single-quoted strings for defining string literals, we only need to escape the single quote inside the string. While there is no need to escape double-quote and can be written exactly.
Use single quotes for literal char s, double quotes for literal String s, like so: char c = 'a'; String s = "hello"; They cannot be used any other way around (like in Python, for example).
A string literal is bracketed by either single quotes ( ' ) or double quotes ( " ). When single quotes bracket a string literal, the value of the literal is the value within the quotes. When double quotes are used, any references to variables or expressions within the quotes are interpolated.
Single quotes need to be escaped by backslash in single-quoted strings, and double quotes in double-quoted strings.
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 '
).
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 = '\'';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With