我一直在准备 OCPJP 21 考试。在学习自动装箱时,我对以下代码片段有一个疑问:
class CharacterAutoboxing {
public static void main(String args[]) {
Character p = 97;
System.out.println(p);
Long l = 116L;
System.out.println(l);
// p = (int)l.longValue();
p = (char)(int)l.longValue();
System.out.println(p);
} // end of main
}
我的查询是Character p = 97
编译器允许的。97 是 int。因此 int 被自动装箱为字符。
那为什么p = (int)l.longValue();
不允许呢?编译器给出异常,因为 int 不能转换为 Character