java int 运算,int上的基本算术运算 - Java

I recently noticed an idiosyncrasy of Java regarding basic arithmetic operations in Java. With the following code

byte a = 3;

byte b = 4;

byte c = a * b;

I get a "type mismatch" compilation error...

Are basic arithmetic operations in Java (+, -, *, /) only performed on primitive data types of int and higher order (long, double, etc.), whereas arithmetic operations on byte and short are first cast to int and then evaluated?

解决方案

Operations on byte, char and short are widened to int unless the compiler can determine the value is in range.

final byte a = 3, b = 4;

byte c = a * b; // compiles

final byte a = 3, b = 40;

byte c = a * b; // compiles

final int a = 3, b = 4;

byte c = a * b; // compiles !!

but

byte a = 3, b = 4;

byte c = a * b; // doesn't compile as the result of this will be `int` at runtime.

final byte a = 30, b = 40;

byte c = a * b; // doesn't compile as the value is too large, will be an `int`

BTW This compiles even though it results in an overflow. :]

final int a = 300000, b = 400000;

int c = a * b; // compiles but overflows, is not made a `long`

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值