java int to short,Java - 从Int到Short的显式转换

Can someone please explain why this following statement:

short value = (short) 100000000;

System.out.println(value);

Gives me:

16960

Knowing that the maximum value of a short in Java is 32767 correct?

解决方案

With your value of 100 million, I get -7936. I can only get 16960 if I change 100 million to 1 million.

The reason is that short values are limited to -32768 to +32767, and Java only keeps the least significant 16 bits when casting to a short (a narrowing primitive conversion, JLS 5.1.3). Effectively this operation: 1 million mod 2^16 (16 bits in a short) is 16960.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值