Is there a difference between single and double quotes in Java?

Is there a difference between single and double quotes in Java?

+72
java syntax
Jan 13 '09 at 15:52
source share
4 answers

Use single quotes for char s literal, double quotes for String s literal, for example:

 char c = 'a'; String s = "hello"; 

They cannot be used in any other way (for example, in Python).

+114
Jan 13 '09 at 15:54
source share

A char is a single UTF-16 character, that is, a letter, number, punctuation mark, tab, space, or something similar.

A char literal - either a single character enclosed in single quotes, such as

 char myCharacter = 'g'; 

or an escape sequence or even a unicode escape sequence:

 char a = '\t'; // Escape sequence: tab char b = '\177' // Escape sequence, octal. char c = '\u03a9' // Unicode escape sequence. 

It is worth noting that Unicode escape sequences are processed very early at compile time, and therefore using '\ u00A' will result in a compiler error. For special characters, it is better to use escape sequences, i.e. '\ n' instead of '\ u00A'.

Double quotes for String , you should use the "double quotes escape sequence" ( \" ) inside strings, where otherwise it would end the string.
For example:

 System.out.println("And then Jim said, \"Who at the door?\""); 

There is no need to avoid double quotes inside single quotes.
The following line is legal in Java:

 char doublequote = '"'; 
+30
Jan 13 '09 at 16:03
source share

Consider these lines of code (Java):

 System.out.println("H"+"A"); //HA System.out.println('H'+'a'); //169 

1) The first line is the concatenation of H and A , which will lead to HA (string literal)

2) Secondly, we add the values โ€‹โ€‹of two char, which according to the ASCII table are H = 72 and A = 97, which means that we add 72+97 , like ('H'+'a') .

3) Consider another case where we would have:

 System.out.println("A"+'N');//AN 

In this case, we are dealing with the concatenation of String A and char N , which will lead to AN .

+4
Mar 17 '17 at 16:18
source share

A single quote indicates a character, and a double quote indicates a string ..

char c = 'c';

'c' -----> c - character

String s = "stackoverflow";

"stackoverflow" ------> stackoverflow is a string (e.g. collection, if characters)

0
Apr 13 '17 at 13:21
source share



All Articles