Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 368
Naetmul Avatar asked May 21 '13 07:05

Naetmul


People also ask

Do I need to escape single quote in Java?

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.

Should I use single or double quotes Java?

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

Can you use single quotes in Java for strings?

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.

Do I need to escape single quote?

Single quotes need to be escaped by backslash in single-quoted strings, and double quotes in double-quoted strings.


2 Answers

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

like image 97
Cory Kendall Avatar answered Oct 06 '22 03:10

Cory Kendall


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 = '\''; 
like image 21
Jamie Avatar answered Oct 06 '22 02:10

Jamie