Java编译器通过`(byte)+(char) - (int)+(long) - 1`解释什么? [英] What does Java compiler interprets by `(byte) + (char) - (int) + (long) - 1`?
问题描述
可能重复:
使用强制转换为原始类型的奇怪java行为
为什么这段代码用Java编写,
Why does this code in Java,
int i = (byte) + (char) - (int) + (long) - 1;
System.out.println(i);
打印1?为什么它甚至可以编译?
prints 1? Why does it even compile?
来源: Java Code Geeks
推荐答案
你正在做的是将类型转换与一元运算符组合。
What you are doing is combining type casts with unary operators.
所以让我们看看:
首先,你有值 -1
,你转换为类型 long
。
First, you have the value -1
, which you cast to the type long
.
然后,你执行一元操作 +
,它不会更改该值,因此您仍然有(长)-1
。
Then, you perform the unary operation +
, which doesn't change the value, so you still have (long) -1
.
然后,你将它转换为int,所以我们现在有 int -1
。然后,你使用一元运算符 -
,所以我们有 - ( - 1)
,这是 1
。
Then, you cast it to int, so we now have int -1
. Then, you use unary operator -
, so we have -(-1)
, which is 1
.
然后你把它投到char,所以我们有 char 1
。然后,你使用一元运算符 +
,所以你仍然有 1
。
Then you cast it to char, so we have char 1
. Then, you use unary operator +
, so you still have 1
.
最后,该值被转换为 byte
,因此你有 byte 1
。然后再次(隐式)转换为 int
。
Finally, the value is cast to byte
, so you have byte 1
. And then it is once again (implicitly) cast to int
.
这篇关于Java编译器通过`(byte)+(char) - (int)+(long) - 1`解释什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!