简体   繁体   中英

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 .

Is this fine in 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.

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!!

just think of it this way: int j = +i would correspond to int j = i . Therefore, -+i or +-i would be -i .

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 ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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