简体   繁体   English

奇怪的Java行为

[英]Strange java behaviour

Can anyone explain me this 谁能向我解释一下

int i=2;
int j=+-i;//-+i; 

the value of j=-2 in either case of +-i or -+i . +-i-+i任何一种情况下, j=-2的值。

Is this fine in Java ? Java很好吗? or should this be a compiler error? 还是应该是编译器错误?

Thankx in advance. 提前感谢。

It's fine - you've just got two unary operators together. 很好-您只有两个一元运算符。 So it's either: 所以是:

int j = +(-i);

or 要么

int j = -(+i);

See sections 15.15.3 and 15.15.4 of the JLS for these two operators. 有关这两个运算符,请参见JLS的15.15.315.15.4

This is absolutely fine. 绝对好 Go through the Unary Operators in java 通过Java中的一元运算符

Both the cases are similar, the ultimate result stays same with the same operations performed in different order!! 两种情况都是相似的,但最终结果与以不同顺序执行的相同操作相同!

just think of it this way: int j = +i would correspond to int j = i . 只是这样想: int j = +i对应于int j = i Therefore, -+i or +-i would be -i . 因此, -+i+-i将是-i

You're applying two unary operators to i : 您正在将两个一元运算符应用于i

int j = +-i;

is equivalent to 相当于

int j = +(-i);

and similarly for -+i . 同样适用于-+i The outcome is the same as negating i unless i is equal to Integer.MIN_VALUE (in which case j ends up equal to i ). 结果与否定i相同,除非i等于Integer.MIN_VALUE (在这种情况下, j最终等于i )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM