Strings and Characters
String and char
A double-quoted literal is a string; a single-quoted literal is a character. These original examples intentionally fail:
char myChar = "A"; // Error: String is not char.
String myString = 'A'; // Error: char is not String.
Use charAt(index) to obtain one UTF-16 code unit from a string:
char myChar = "A".charAt(0);
String myString = "" + 'C'; // "C"
int and char
int code = 'A'; // 65
char letter = (char) 65; // 'A'
Review clarification
charholds a UTF-16 code unit from 0 to 65,535. An explicit cast from an out-of-rangeintstill compiles and keeps the low 16 bits. Some Unicode characters require twocharvalues.
Source: Java types §4.2.1.
String constant pool
Equal string literals share an interned string object. Variable names do not determine this sharing.
String first = "Hello";
String second = "Hello";
String third = new String("Hello");
System.out.println(first == second); // true
System.out.println(first == third); // false
System.out.println(first.equals(third)); // true
Correction to the original notes
The pool contains string objects, not variables. Sharing depends on the literal’s contents, rather than declaring another variable with the same name.
new String(...)creates a distinct object;.equals(...)still compares its text.
Sources: String literals §3.10.5, String API.
Related: Equality · String methods