23.07.2013 Views

Java IO.pdf - Nguyen Dang Binh

Java IO.pdf - Nguyen Dang Binh

Java IO.pdf - Nguyen Dang Binh

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

14.5 The char Data Type<br />

<strong>Java</strong> I/O<br />

The char primitive data type in <strong>Java</strong> is a two-byte unsigned integer whose values range from<br />

to 65,535. char variables may be assigned from int literals, like this:<br />

char exclamationPoint = 33;<br />

In the virtual machine, chars are promoted to ints in arithmetic operations like addition and<br />

multiplication. Therefore, operations more complicated than a simple assignment require an<br />

explicit cast to char, like this:<br />

char a = 97;<br />

char b = (char) (a + 1);<br />

In practice, chars are rarely used in arithmetic operations. Instead, they're given symbolic<br />

meanings through mappings to particular elements of the Unicode character set. For instance,<br />

33 is the Unicode (and ASCII) character for the exclamation point (!). 97 is the Unicode (and<br />

ASCII) character for the small letter a. When the Unicode and printable ASCII characters<br />

converge, as they do for values between 32 and 127, a char may be written in <strong>Java</strong> source<br />

code as a char literal. This is the desired ASCII character between single quote marks, like<br />

this:<br />

char exclamationPoint = '!';<br />

char a = 'a';<br />

char b = 'b';<br />

For characters outside this range, you can assign values to chars using Unicode escape<br />

sequences, like this:<br />

char tab = '\u0009';<br />

char softHyphen = '\u00AD';<br />

char sigma = '\u03C3';<br />

char squareKeesu = '\u30B9';<br />

14.5.1 The java.lang.Character Class<br />

As for the other primitive data types, the core API includes a type wrapper class for char<br />

values. This is java.lang.Character :<br />

public final class Character implements Serializable<br />

In <strong>Java</strong> 2 Character also implements Comparable:<br />

public final class Character implements Serializable, Comparable // <strong>Java</strong> 2<br />

14.5.1.1 Constructor<br />

This class has a single constructor:<br />

public Character(char value)<br />

For example:<br />

348

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!