2.9. Storing Characters

Variables of type char store a single character code. They each occupy 16 bits, or 2 bytes, in memory because all characters in Java are stored as Unicode. To declare and initialize a character variable myCharacter you could use the statement:

char myCharacter = 'X';

This initializes the variable with the Unicode character representation of the letter 'X'. You must always put single quotes as delimiters for a character literal in a statement as in this example, '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 as delimiters here because they are used to delimit a character string. A character string such as "X" is quite different from the literal of type char, 'X'.

2.9.1. Character Escape Sequences

In general, the characters that you will be able to enter directly from your keyboard will be a function of the keys you have available and the set of character codes they map to according to your operating system. Whatever that is, it will be a small subset of the characters defined by the Unicode encoding. To enable you to enter any Unicode character as part of your program source code 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 that is often, but not exclusively, defined by its code. A backslash ...

Get Ivor Horton's Beginning Java™ 2, JDK™ 5th Edition 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.