問題描述
我有 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);
但要小心溢出/下溢.
這篇關于為什么字節的總和是整數?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!