Java Reference
In-Depth Information
Table 3-2. List of Character Escape Sequences
Character Escape Sequence
Description
'\n'
A linefeed
'\r'
A carriage return
'\f'
A form feed
'\b'
A backspace
'\t'
A tab
'\\'
A backslash
'\"'
A double quote
'\''
A single quote
A character literal expressed in the form of a character escape sequence consists of two characters—a backslash
and a character following the backslash. However, they represent only one character. There are only eight character
escape sequences in Java. You cannot define your own character escape sequences.
char c1 = '\n'; // Assigns a linefeed to c1
char c2 = '\"'; // Assigns double quote to c2
char c3 = '\a'; // A compile-time error. Invalid character escape sequence
A character literal can also be expressed as a Unicode escape sequence in the form '\uxxxx' , Here, \u (a backslash
immediately followed by a lowercase u ) denotes the start of the Unicode escape sequence, and xxxx represents exactly
four hexadecimal digits. The value represented by xxxx is the Unicode value for the character. The character 'A' has
the Unicode value of 65. The value 65 in decimal can be represented in hexadecimal as 41 . So, the character 'A' can
be expressed in Unicode escape sequence as '\u0041' . The following snippet of code assigns the same character 'A'
to the char variables c1 and c2 :
char c1 = 'A';
char c2 = '\u0041'; // Same as c2 = 'A'
A character literal can also be expressed as an octal escape sequence in the form '\nnn' . Here, n is an octal digit
(0-7). The range for the octal escape sequence is '\000' to '\377' . The octal number 377 is the same as the decimal
number 255 . Therefore, using octal escape sequence, you can represent characters whose Unicode code range from 0
to 255 decimal integers.
A Unicode character set (code range 0 to 65535) can be represented as a Unicode escape sequence ( '\uxxxx' ).
Why does Java have another octal escape sequence, which is a subset of Unicode escape sequence? The octal escape
sequences exist to represent characters for compatibility with other languages that use 8-bit unsigned chars to
represent a character. Unlike a Unicode escape sequence, where you are always required to use four hexadecimal
digits, in an octal escape sequence you can use one, two, or three octal digits. Therefore, an octal escape sequence
may take on a form '\n' , '\nn' , or '\nnn' , where n is one of the octal digits 0, 1, 2, 3, 4, 5, 6, and 7. Some examples of
an octal escape sequence are as follows:
char c1 = '\52';
char c2 = '\141';
char c3 = '\400'; // A compile-time error. Octal 400 is out of range
char c4 = '\42';
char c5 = '\10'; // Same as '\n'
 
Search WWH ::




Custom Search