Java Language Primitive Data Types The char primitive


A char can store a single 16-bit Unicode character. A character literal is enclosed in single quotes

char myChar = 'u';
char myChar2 = '5';
char myChar3 = 65; // myChar3 == 'A'

It has a minimum value of \u0000 (0 in the decimal representation, also called the null character) and a maximum value of \uffff (65,535).

The default value of a char is \u0000.

char defaultChar;    // defaultChar == \u0000

In order to define a char of ' value an escape sequence (character preceded by a backslash) has to be used:

char singleQuote = '\'';

There are also other escape sequences:

char tab = '\t';
char backspace = '\b';
char newline = '\n';
char carriageReturn = '\r';
char formfeed = '\f';
char singleQuote = '\'';
char doubleQuote = '\"'; // escaping redundant here; '"' would be the same; however still allowed
char backslash = '\\';
char unicodeChar = '\uXXXX' // XXXX represents the Unicode-value of the character you want to display

You can declare a char of any Unicode character.

char heart = '\u2764';
System.out.println(Character.toString(heart)); // Prints a line containing "❤".

It is also possible to add to a char. e.g. to iterate through every lower-case letter, you could do to the following:

for (int i = 0; i <= 26; i++) {
    char letter = (char) ('a' + i);