Java Reference
In-Depth Information
4.3.3 Casting between
char
and Numeric Types
A
char
can be cast into any numeric type, and vice versa. When an integer is cast into a
char
,
only its lower 16 bits of data are used; the other part is ignored. For example:
char
ch = (
char
)
0XAB0041
;
// The lower 16 bits hex code 0041 is
// assigned to ch
System.out.println(ch);
// ch is character A
When a floating-point value is cast into a
char
, the floating-point value is first cast into an
int
, which is then cast into a
char
.
char
ch = (
char
)
65.25
;
// Decimal 65 is assigned to ch
System.out.println(ch);
// ch is character A
When a
char
is cast into a numeric type, the character's Unicode is cast into the specified
numeric type.
int
i = (
int
)
'A'
;
// The Unicode of character A is assigned to i
System.out.println(i);
// i is 65
Implicit casting can be used if the result of a casting fits into the target variable. Otherwise,
explicit casting must be used. For example, since the Unicode of
'a'
is
97
, which is within
the range of a byte, these implicit castings are fine:
byte
b =
'a'
;
int
i =
'a'
;
But the following casting is incorrect, because the Unicode
\uFFF4
cannot fit into a byte:
byte
b =
'\uFFF4'
;
To force this assignment, use explicit casting, as follows:
byte
b = (
byte
)
'\uFFF4'
;
Any positive integer between
0
and
FFFF
in hexadecimal can be cast into a character
implicitly. Any number not in this range must be cast into a
char
explicitly.
All numeric operators can be applied to
char
operands. A
char
operand is automati-
cally cast into a number if the other operand is a number or a character. If the other oper-
and is a string, the character is concatenated with the string. For example, the following
statements
numeric operators on
characters
int
i =
'2'
+
'3'
;
// (int)'2' is 50 and (int)'3' is 51
System.out.println(
"i is "
+ i);
// i is 101
int
j =
2
+
'a'
;
// (int)'a' is 97
System.out.println(
"j is "
+ j);
// j is 99
System.out.println(j +
" is the Unicode for character "
+ (
char
)j);
// 99 is the Unicode for character c
System.out.println(
"Chapter "
+
'2'
);
display
i is 101
j is 99
99 is the Unicode for character c
Chapter 2
Search WWH ::
Custom Search