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, char
s are promoted to
int
s 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, char
s 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
char
s 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 the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.