Java Reference
In-Depth Information
Storing Characters
Variables of the type char store a single character. They each occupy 16 bits, two bytes, in memory
because all characters in Java are stored as Unicode. To declare and initialize a character variable
myCharacter you would use the statement:
char myCharacter = 'X';
This initializes the variable with the Unicode character representation of the letter 'X' . You must put
single quotes around a character in a statement - 'X' . This is necessary to enable the compiler to
distinguish between the character 'X' and a variable with the name X . Note that you can't use double
quotes here as they are used to delimit a character string. A character string such as "X" is quite
different from the literal of type char , 'X' .
Character Escape Sequences
If you are using an ASCII text editor you will only be able to enter characters directly that are defined
within ASCII. You can define Unicode characters by specifying the hexadecimal representation of the
character codes in an escape sequence. An escape sequence is simply an alternative means of specifying
a character, often by its code. A backslash indicates the start of an escape sequence, and you create an
escape sequence for a Unicode character by preceding the four hexadecimal digits of the character by
\u . Since the Unicode coding for the letter X is 0x0058 (the low order byte is the same as the ASCII
code), you could also declare and define myCharacter with the statement:
char myCharacter = '\u0058';
You can enter any Unicode character in this way, although it is not exactly user-friendly for entering a
lot of characters.
You can get more information on the full Unicode character set on the Internet by
visiting http://www.unicode.org/ .
As you have seen, we can write a character string (a String literal as we will see in Chapter 4)
enclosed between double quotes. Because the backslash indicates the beginning of an escape sequence
in a character string, you must use an escape sequence to specify a backslash character itself in text
strings, \\ . Since a single quote is used to delimit characters, and we use a double quote to delimit a
text string, we also need escape sequences for these. You can define a single quote with the escape
sequence \' , and a double quote with \" . For example, to produce the output:
"It's freezing in here", he said coldly.
you could write:
System.out.println("\"It\'s freezing in here\", he said coldly.");
Search WWH ::




Custom Search