Java Characters
The char type stores a single character, such as a letter, a digit, or a symbol. Under the hood every char is actually a number, which leads to some surprising and useful behaviour.
Declaring a char
A char literal is written with single quotation marks around exactly one character. This is different from a String, which uses double quotes and can hold any number of characters, including none at all.
Single characters
public class Main {
public static void main(String[] args) {
char grade = 'A';
char symbol = '$';
char digit = '7';
System.out.println(grade);
System.out.println(symbol);
System.out.println(digit);
}
}Characters are secretly numbers
Each char is stored as a Unicode code point, a whole number that identifies the character. Because of this, you can use a char in arithmetic, and you can create one from a number. The letter 'A', for example, is number 65.
The number behind a char
public class Main {
public static void main(String[] args) {
char letter = 'A';
int code = letter; // 65
char next = (char) (letter + 1); // 'B'
System.out.println(code);
System.out.println(next);
}
}Escape sequences
Some characters cannot be typed directly, such as a new line or a quotation mark. For these, Java uses escape sequences: a backslash followed by a code that stands for the special character.
Using an escape sequence
public class Main {
public static void main(String[] args) {
char tab = '\t';
char newline = '\n';
System.out.print("Name:" + tab + "Ada");
System.out.print(newline);
System.out.print("Done");
}
}- Use single quotes for a char and double quotes for a String.
- Because a char is a number, comparisons like myChar >= 'a' work as you would expect.
- Convert a char digit like '7' to its numeric value with an expression such as digit - '0'.
- A char holds one Unicode unit, which covers letters from many of the world's writing systems.