Java类型转换详解

Java76

最近,一个学生问:我不记得自动类型转换,是大到小还是小到大

[En]

Recently, a student asked: I can't remember the automatic type conversion, whether it is big to small or small to big

其实这个不用死记硬背,很好理解,我们拿 intshort 来举例:

int4 字节,也就是 32 bit,所以 int 的范围在 [-231,231-1] 也就是大概 [-21亿,21亿]

short2 字节,也就是 16 bit,所以 short 的范围在 [-215,215-1] 也就是 [-32768,32767]

所以我们可以很明显的发现一个问题, shortint 是无论如何都不会超出范围的

既然不会超出范围,当然语言就可以自动为我们进行转化

如果 int 转 short 则需要强转,也就是:

```java
public static void main(String[] args) {
short a = 1;
int b = 2;
short c = (short) (a + b);
}

输入验证码查看隐藏内容

扫描二维码关注本站微信公众号 Johngo学长
或者在微信里搜索 Johngo学长
回复 svip 获取验证码
wechat Johngo学长