Witscale Test Center

7.3 Literals >  7.3.2 Character literals


 7.3.2 Character literals

Character literals are defined by enclosing the character value in single quotes. For instance, the following code has the character literal ‘w’ and ‘y’:

 

char choice = 'w';     // character literal is assigned to a variable

if(choice == 'y') {}  // character literal is used in comparison

 

As you can see the literals can be used for other purposes than just while assigning a value. For instance, the second line uses the character literal 'y' in an if condition.

      Enclosing the character itself works fine as long as the character is type-able. What if you want to use the character (as a literal), which is not on the keyboard? In that case, you need to represent the character literal using hexadecimal[‡‡‡‡‡‡‡‡] values. The hexadecimal value (in the range 0 to 216 –1) represents a value for a character in Unicode notation. Therefore, it is prefixed with \u (Unicode escape) followed by the hexadecimal value:

 

char ch = '\u002A';    // character literal using a hex code

 

The 002A is a hexadecimal value for some character in Unicode encoding. You need to give all four digits of the hexadecimal value for Unicode escaping. For instance, ‘\u20’ is invalid; you must use ‘\u0020’ for a valid character literal.

A character literal always represents exactly one character. You cannot enclose more than one character in single quotes. There are certain character literals for special (escape) characters such as the newline (\n), tab(\t) or carriage return(\r) and so on. Like other literals, you only need to enclose these special characters in single quote to make them a literal as:

 

 char ch = '\r';

 

Some other special character literals in Java are '\\'(slash itself), '\f' (form feed), '\''(single quote).