初学 Java 时, 老师提出了一个很有意思的现象:
//基础数据类型之间进行转换
int number = 68;
char chart = (char)number;
System.out.println("number = " + number);
System.out.println("chart = " + chart);
char chart_2 = 'E';
int number_2 = chart_2;
System.out.println("number_2 = " + number_2);
System.out.println("chart_2 = " + chart_2);
//****************打印结果*****************
number = 68
chart = D
number_2 = 69
chart_2 = E
当时很迷惑,今天看到 《Think in Java》中进行了详细的解释。
大意:在 char、byte 和 short 中,您可以看到使用算术运算符进行提升的效果。对任何这些类型的每个算术运算都会产生一个 int 结果,该结果必须显式转换回原始类型(可能会丢失信息的缩小转换)以分配回该类型。但是,对于 int 值,您不需要强制转换,因为一切都已经是 int 了。
这就是为什么可以直接用 int 数据类型存储 char 值,且可以直接打印,值为 十进制的ASCII 码 。
In char, byte, and short, you can see the effect of promotion with the arithmetic
operators. Each arithmetic operation on any of those types produces an int result,
which must be explicitly cast back to the original type
(a narrowing conversion that might lose information) to assign back to that type.
With int values, however, you do not need to cast, because everything is already an int.
You can see that, with the exception of boolean, any primitive type can be cast to any
other primitive type.