Can anyone explain me this
int i=2;
int j=+-i;//-+i;
the value of j=-2 in either case of +-i or -+i.
Is this fine in Java ? or should this be a compiler error?
Thankx in advance.
4 Answers 4
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.
Comments
This is absolutely fine. Go through the Unary Operators in java
Both the cases are similar, the ultimate result stays same with the same operations performed in different order!!
Comments
just think of it this way: int j = +i would correspond to int j = i. Therefore, -+i or +-i would be -i.
Comments
You're applying two unary operators to i:
int j = +-i;
is equivalent to
int j = +(-i);
and similarly for -+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).