忽略char
,Java將促進數值類型是這樣的:
byte > short > int > long > float > double
這些被稱爲擴大轉換。詳情請參閱JLS §5.1.2. Widening Primitive Conversion。
二元運算將推動到int
,long
,float
,或double
,取其來自操作者的兩個值最接近的,即結果將永遠byte
或short
。例如:byte + short
將推動雙方到int
。詳情請參閱JLS §5.6.2. Binary Numeric Promotion。
賦值操作符也會做拓寬值轉換,用額外的規則byte
類型,short
的常量表達式,或int
會經過narrowing conversion如果變量的類型是byte
或short
,並且常量表達式的值可以在類型中表示。請注意,沒有規定將double
縮小到float
。詳情請參閱JLS §5.2. Assignment Contexts。
因此,對於您的代碼:
double x = 39.21; // double constant to double (identity conversion)
float y = 2.1; // fails because double constant cannot promote to float
如果碼編過,什麼是x + y
數據類型?
x + y // double + float promotes to double
答:double
下一個部分:
short x = 14; // narrowing conversion of int constant to short
float y = 13; // widening conversion of int constant to float
double z = 30; // widening conversion of int constant to double
現在,什麼是x * y/z
數據類型?
x * y // short * float promotes to float
(x * y)/z // (float)/double promotes to double
答案:double
y被分配爲浮動。字面表達式「2.1」(沒有明確的尾部f)是雙精度。它不會編譯,因爲你不能在較小的浮點數中填入較大的雙精度值。 –
但是,您可以將int 13分配給浮點數,因爲int可以提升爲浮點數。 –
相關:http://stackoverflow.com/questions/28361456/why-explicit-type-casting-required-from-double-to-float-but-not-from-int-to-byte –