最近,一个学生问:我不记得自动类型转换,是大到小还是小到大
[En]
Recently, a student asked: I can't remember the automatic type conversion, whether it is big to small or small to big
其实这个不用死记硬背,很好理解,我们拿 int 和 short 来举例:
int 是 4 字节,也就是 32 bit,所以 int 的范围在 [-231,231-1] 也就是大概 [-21亿,21亿]
short 是 2 字节,也就是 16 bit,所以 short 的范围在 [-215,215-1] 也就是 [-32768,32767]
所以我们可以很明显的发现一个问题, short 转 int 是无论如何都不会超出范围的
既然不会超出范围,当然语言就可以自动为我们进行转化
如果 int 转 short 则需要强转,也就是:
```java
public static void main(String[] args) {
short a = 1;
int b = 2;
short c = (short) (a + b);
}