問題描述
public class Java{
public static void main(String[] args){
final byte x = 1;
final byte y = 2;
byte z = x + y;//ok
System.out.println(z);
byte a = 1;
byte b = 2;
byte c = a + b; //Compiler error
System.out.println(c);
}
}
如果涉及任何 int 大小或更小的表達式的結果始終是 int,即使兩個字節的總和適合一個字節.
If the result of an expression involving anything int-sized or smaller is always an int even if the sum of two bytes fit in a byte.
為什么當我們添加兩個適合一個字節的最終字節時會發生這種情況?沒有編譯器錯誤.
推薦答案
來自JLS 5.2 賦值轉換
此外,如果表達式是 byte、short、char 或 int 類型的常量表達式(第 15.28 節):- 如果類型為變量是 byte、short 或 char,以及常量的值表達式可以用變量的類型來表示.
In addition, if the expression is a constant expression (§15.28) of type byte, short, char, or int: - A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable.
簡而言之,表達式的值(在編譯時是已知的,因為它是一個常量表達式)可以用字節變量的類型來表示.
In short the value of the expression (which is known at compile time, because it is a constant expression) is representable in the type of the variable that is byte.
考慮你的表達方式
final byte x = 1;
final byte y = 2;
byte z = x + y;//This is constant expression and value is known at compile time
因此,當求和適合字節時,它不會引發編譯錯誤.
So as summation fits into byte it does not raise an compilation error.
如果你這樣做了
final byte x = 100;
final byte y = 100;
byte z = x + y;// Compilation error it no longer fits in byte
這篇關于為什么我不能添加兩個字節并獲得一個 int,而我可以添加兩個最終字節獲得一個字節?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!