Although int i = 'a'
works fine, converting the same to Integer
is not allowed, because it requires a boxing conversion.
Java's boxing conversion is defined only for eight cases:
- From type
boolean
to type Boolean
- From type
byte
to type Byte
- From type
short
to type Short
- From type
char
to type Character
- From type
int
to type Integer
- From type
long
to type Long
- From type
float
to type Float
- From type
double
to type Double
Since 'a'
is a char
literal, Java does not allow conversion from char
to Integer
: a character literal is always of type char
.
However, when you write
Character ch2 = 97;
Java compiler sees that 97 is in the valid range for char
(i.e. 0..65535), so it treats 97
as char
, not int
, and allows the boxing conversion. Trying the same with an out-of-range constant produces an error:
Character ch3 = 65536; // error: incompatible types: int cannot be converted to Character