Why is the sum of bytes integer?(为什么字节的总和是整数?)
问题描述
我有 tyo 字节变量
I have tyo byte variable
byte a = 3;
byte b = 4;
如果我把它们相加,sum的值是整数.
If I sum them, the value of sum is integer.
byte z = a+b //error, left side is byte, right side is integer
为什么 a+b 是 int?
Why a+b is int?
推荐答案
因为Java 语言规范 这么说
对操作数执行二进制数字提升(第 5.6.2 节).
Binary numeric promotion is performed on the operands (§5.6.2).
注意二进制数值提升执行值集转换(§5.1.13) 并且可以执行拆箱转换 (§5.1.8).
Note that binary numeric promotion performs value set conversion (§5.1.13) and may perform unboxing conversion (§5.1.8).
数字操作数上的加法表达式的类型是提升的其操作数的类型.
The type of an additive expression on numeric operands is the promoted type of its operands.
并且,关于数字推广,
加宽基元转换(第 5.1.2 节)用于转换或两个操作数均由以下规则指定:
Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules:
- [...]
- 否则,两个操作数都转换为
int
类型.
所以 byte
值被提升为 int
值并相加.表达式的结果是提升的类型,因此是 int
.
So the byte
values are promoted to int
values and added up. The result of the expression is the promoted type, therefore an int
.
你可以简单地转换结果
byte z = (byte) (b + a);
但要小心溢出/下溢.
这篇关于为什么字节的总和是整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么字节的总和是整数?


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