java 字节单位计算,Java:字节上的算术运算

What happened to my code? The following code worked for integer type of data, but couldn't work for byte type of data.

public class Exchange {

public static void main(String[] args) {

//int a = 23, b = 44;

byte a = 23, b = 44;

a = a + b;

b = a - b;

a = a - b;

System.out.println("a=" + a + "b=" + b);

}

}

I know that the data-type byte can hold data of the range -2^(8-1) to -1+2^(8-1). But I'm using 23 & 44, so it's less than 127.

Here I got error message "incompatible types: possible lossy conversion from int to byte".

解决方案

If you want to perform an arithmetic operation on byte and assign it back to a byte variable you should explicitly let the compiler know that "you know what you're doing" otherwise you'll get the the error that you're losing information by converting int (the outcome of the arithmetic operation) to byte (on the left side).

To fix this, cast the outcome of the arithmetic operation back to byte:

byte a = 23, b = 44;

a = (byte) (a + b);

b = (byte) (a - b);

a = (byte) (a - b);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值