在转换的情况下Java编译时错误 [英] Java compile time error in case of casting

查看:161
本文介绍了在转换的情况下Java编译时错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码给出了编译时错误类型不匹配:无法从int转换为字节

The below code gives me compile time error Type mismatch: cannot convert from int to byte

int i = 10;
byte b = i;

但是下面没有

 final int i = 10;
 byte b = i;

我不明白为什么编译器在最终的情况下表现如何?

I don't understand why compiler is behaving in case of final?

推荐答案

我认为这是因为10适合一个字节,但如果整数超过8位,则无法正常执行这个任务了。

I think it's because 10 fits in a byte, but if the integer was something that takes more than 8 bits then it wouldn't be able to properly do this assignment anymore.

编辑

为了澄清,使其成为最终允许编译器处理int作为常量,因此它可以进行常量折叠。它可能会阻止使用非final int赋值,因为它在编译时不知道该值,并且它可能比字节可以容纳的值大。

To clarify, making it final is allowing the compiler to treat the int as a constant so it can do constant folding. It's probably preventing the assignment with the non-final int because it doesn't know that value at compile time and it could be way bigger than what a byte can hold.

这篇关于在转换的情况下Java编译时错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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