为什么我得到类型不匹配:无法从int转换为byte [英] Why i am getting type mismatch: cannot convert from int to byte

查看:206
本文介绍了为什么我得到类型不匹配:无法从int转换为byte的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Test
{  
   public static void main(String[] args) 
   { 
     byte t1 = 111;
     byte t2 =11;
     byte t3 = t1+t2;

     System.out.println(t1+t2);   

   }  
}  

在eclipse中显示错误无法从int转换为byte .Here是122,其范围在字节范围内。所以为什么我在这里收到此错误。

In eclipse it is showing error cannot convert from int to byte.Here sum is 122 which range in the byte range.So why i am getting this error here.

提前致谢...

推荐答案

当您对字节进行数学运算时,Java会进行扩展(自动类型提升) )将字节(隐式上升)转换为整数这种情况。所以当你执行时

When you do mathematical operations on byte, Java do Widening( automatic type promotion) to byte(implicitly up casted) to integer this case. so when you perform

 byte t3 = t1+t2; //  t1+t2; will be evaluated as integer.

由于t1 + t2结果比字节宽,所以你需要将它向下转换为字节。

As t1+t2 result is wider than byte so you need to downcast it to byte.

删除编译错误。

 byte t3 = (byte) (t1+t2); // typecast to byte

有关详细信息,请阅读 JLS 5.1.2

For more information please read JLS 5.1.2

这篇关于为什么我得到类型不匹配:无法从int转换为byte的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆