0

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.

asked Dec 7, 2011 at 11:57

4 Answers 4

11

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.

answered Dec 7, 2011 at 11:58
Sign up to request clarification or add additional context in comments.

Comments

2

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

answered Dec 7, 2011 at 12:00

Comments

2

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

answered Dec 7, 2011 at 12:01

Comments

2

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

answered Dec 7, 2011 at 12:02

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.