[英]what happens when a negative integer is type cast to long in java?
int i = 0;
long ll = 0L;
i = -1 - 2; // -3
i = (int) -1 - 2; // -3
ll = (long) - (int) -1 - 2;// -1
i = (int) +(long) -(int) -1 - 2;//-1
ll = (long) +(int) -1 - 2; // -3
In the above program at the line 在上面的程序中就行了
ll = (long) - (int) -1-2;
ll
value is -1
. ll
值为-1
。 How does its value becomes -1
just by type casting? 仅通过类型转换,其值如何变为-1
? Shouldn't it be like 3 or -3? 不应该是3或-3吗?
i = (int) +(long) -(int) -1 - 2;
unary operator will be evaluated first then binary because of unary operator is higher precedence than binary operator. 一元运算符将首先被评估,然后是二进制,因为一元运算符的优先级高于二元运算符。
so -(int) -1
will be evaluated first and it will become +1
所以-(int) -1
将首先被求值,它将变为+1
then +(long)+1
will be +1
那么+(long)+1
将为+1
and after that (int)+1
will be evaluated so it will become +1
然后(int)+1
将被评估,因此它将变为+1
then +1-2
will be evaluated as -1
so you are getting -1
. 那么+1-2
将被评估为-1
因此您得到-1
。 same operation will be performed for other statements. 其他语句将执行相同的操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.