Java: why do I receive the error message quot;Type mismatch: cannot convert int to bytequot;(Java:为什么我会收到错误消息“类型不匹配:无法将 int 转换为字节?)
问题描述
如果您声明 byte 或 short 类型的变量并尝试对它们执行算术运算,则会收到错误类型不匹配:无法将 int 转换为 short"(或相应地类型不匹配:无法将 int 转换为字节").
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),字节和短类型的操作数在交给操作员之前会自动提升为 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 大师的后续问题:为什么?byte 和 short 类型是非常好的数字类型.为什么 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 转换为字节"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java:为什么我会收到错误消息“类型不匹配:无法


基础教程推荐
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01