Java:为什么我收到错误消息“类型不匹配:无法将int转换为字节” [英] Java: why do I receive the error message "Type mismatch: cannot convert int to byte"

查看:159
本文介绍了Java:为什么我收到错误消息“类型不匹配:无法将int转换为字节”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果声明byte或short类型的变量并尝试对这些变量执行算术运算,则会收到错误Type mismatch:can int int int to short(或相应的Type mismatch:not int int int to byte)。

If you declare variables of type byte or short and attempt to perform arithmetic operations on these, you receive the error "Type mismatch: cannot convert int to short" (or correspondingly "Type mismatch: cannot convert int to byte").

byte a = 23;
byte b = 34;
byte c = a + b;

在这个例子中,编译错误在第三行。

In this example, the compile error is on the third line.

推荐答案

虽然算术运算符被定义为对任何数字类型进行操作,但根据Java语言规范(5.6.2 Binary Numeric Promotion),类型为byte和short的操作数在传递给运算符之前会自动提升为int。

Although the arithmetic operators are defined to operate on any numeric type, according the Java language specification (5.6.2 Binary Numeric Promotion), operands of type byte and short are automatically promoted to int before being handed to the operators.

要对byte或short类型的变量执行算术运算,必须将表达式括在括号中(其中)操作将按类型int)执行,然后将结果转换回所需的类型。

To perform arithmetic operations on variables of type byte or short, you must enclose the expression in parentheses (inside of which operations will be carried out as type int), and then cast the result back to the desired type.

byte a = 23;
byte b = 34;
byte c = (byte) (a + b);

这是真正的Java专家的后续问题:为什么?字节和短字类型是完美的数字类型。为什么Java不允许对这些类型进行直接算术运算? (答案不是精度损失,因为没有明显的理由首先转换为int。)

Here's a follow-on question to the real Java gurus: why? The types byte and short are perfectly fine numeric types. Why does Java not allow direct arithmetic operations on these types? (The answer is not "loss of precision", as there is no apparent reason to convert to int in the first place.)

更新:jrudolph表明这种行为是基于JVM中可用的操作,具体而言,只实现了全字和双字运算符。因此,对于操作符的字节和短路,它们必须转换为int。

Update: jrudolph suggests that this behavior is based on the operations available in the JVM, specifically, that only full- and double-word operators are implemented. Hence, to operator on bytes and shorts, they must be converted to int.

这篇关于Java:为什么我收到错误消息“类型不匹配:无法将int转换为字节”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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