The char Data Type

The char primitive data type in Java is a two-byte unsigned integer whose values range from to 65,535. char variables may be assigned from int literals, like this:

char exclamationPoint = 33;

In the virtual machine, chars are promoted to ints in arithmetic operations like addition and multiplication. Therefore, operations more complicated than a simple assignment require an explicit cast to char, like this:

char a = 97;
char b = (char) (a + 1);

In practice, chars are rarely used in arithmetic operations. Instead, they’re given symbolic meanings through mappings to particular elements of the Unicode character set. For instance, 33 is the Unicode (and ASCII) character for the exclamation point (!). 97 is the Unicode (and ASCII) character for the small letter a. When the Unicode and printable ASCII characters converge, as they do for values between 32 and 127, a char may be written in Java source code as a char literal. This is the desired ASCII character between single quote marks, like this:

char exclamationPoint = '!';
char a = 'a';
char b = 'b';

For characters outside this range, you can assign values to chars using Unicode escape sequences, like this:

char tab = '\u0009';
char softHyphen = '\u00AD';
char sigma = '\u03C3';
char squareKeesu = '\u30B9';

The java.lang.Character Class

As for the other primitive data types, the core API includes a type wrapper class for char values. This is java.lang.Character :

public final class Character implements Serializable

In Java ...

Get Java I/O now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.