Java Reference
In-Depth Information
If you need to denote a character by its Unicode value, you use the escape
sequence \u followed by its Unicode value in hexadecimal format, as in
'\uF9A4', or octal format, as in '\071'. (The octal format is for the Latin-1
encoding.)
The following CharDemo program demonstrates the use of the char data
type and character literals. Study it carefully and try to determine the output,
which is shown in Figure 2.4. You will likely be surprised.
public class CharDemo
{
public static void main(String [] args)
{
char a = 'A';
char b = (char) (a + 1);
System.out.println(a + b);
System.out.println(“a + b is “ + a + b);
int x = 75;
char y = (char) x;
char half = '\u00AB';
System.out.println(“y is “ + y + “ and half is “ + half);
}
}
In the CharDemo program, a and b are declared as char variables. When b
is assigned to (a + 1), the cast operator is required because the result of
adding 1 to a is an int. We saw this in the IntegerDemo program, when the
sum of two shorts was an int. Java promotes the smaller integer types to
int values before performing any arithmetic.
Adding (a + b) results in the sum of two ints, which is 65 + 66, or 131. The
second println() statement is not adding 'A' and 'B', but concatenating the two
characters. The result of concatenation is a string, in this case “AB”.
Notice in the CharDemo program that the int x is cast to a char. The value 75
corresponds with a 'K', which is the value of y. The variable half demonstrates
using the '\u' escape sequence, and the character '\u00AB' is the 1/2 character.
Figure 2.4
Output of the CharDemo program.
Search WWH ::




Custom Search