[英]Java arithmetic operation and then casting
I have this piece of code. 我有这段代码。
short x = 50,y=40;
short z = (short)(x + y);//THIS COMPILES
short z2 = (short) x + y;//THIS DOESN'T
How come the code snippet of z compiles, while z2 doesn't? z为何不编译z的代码片段? When performing an arithmetic operation on short it will immediately promote it to a int. 当短时执行算术运算时,它将立即提升为int。 however I'm downcasting it back to short but it produces an error. 但是我将其转换为简短版本,但会产生错误。 Please explain. 请解释。 Am I missing anything? 我有什么想念的吗?
This line: 这行:
(short) x + y
Can be understood like this: 可以这样理解:
short + int
Because the type cast only applies for x
, not for the result of the sum. 因为类型转换仅适用于x
,而不适用于总和的结果。 So, the result of the operation returns an int
, thus the compiler exception. 因此,运算结果返回一个int
,从而返回编译器异常。
The second line compiles, because the result of the addition is casted to a short
so it can be assigned to z
, a short
. 第二行进行编译,因为加法的结果强制转换为short
因此可以将其分配给short
z
。
The third line doesn't compile, because the cast to short
only applies to x
, before the addition takes place. 第三行不编译,因为对short
的强制类型转换仅适用于x
,然后才进行加法运算。 The result of the addition of a short
and an int
is an int
, which can't be assigned directly to a short
( z2
). 将short
和int
相加的结果是一个int
,不能将其直接分配给short
( z2
)。
The parentheses in the second line force the order of operations necessary for a short
value to be assigned to a short
variable. 第二行中的括号强制将short
值分配给short
变量所需的操作顺序。
In the z you are casting the final outcome of x+y as a whole to a short and assigned it to a short. 在z中,您将x + y的最终结果作为一个整体强制转换为short,并将其分配为short。
But in the z2 you are casting x to a short and adding it with y gives a int. 但是在z2中,您将x强制转换为short并与y相加得到一个int值。 SO int can't be assigned to a short. SO int不能分配给short。 That is why you get the compile error 这就是为什么您得到编译错误
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.