Could anyone of you tell me how this is executed int x=-5; x+=x<0?2:-2; System.out.println(x); I got the answer as -3. How does -3 gets printed here?
Joined: Jul 30, 2003
Initially, x equals -5. The assignment operator is right-associative, so it'll perform the ternary operation first. The ternary operator performs the logical test x<0, which is true, so it adds the quantity 2 to -5 which equals -3. Had the test been false, the answer would have been to add -2 to -5, producing -7. The ternary operator works like this: test ? true < false You can have any boolean expression for the test, and any valid expression for the true/false operation. Hope that helps!
Give a man a fish, he'll eat for one day. <br />Teach a man to fish, he'll drink all your beer.<br /> <br />Cheers,<br /> <br />Jeff (SCJP 1.4, SCJD in progress, if you can call that progress...)
Joined: Oct 21, 2003
Thank you Jeff.... I missed the fact that assignment operator is right associative.
Joined: May 05, 2000
It's pretty simple... the stuff before the ? is evaluated as a boolean. If it is true then the stuff between the ? and the : is returned. If it is false then the stuff after the : is returned. int x=-5; x+=x<0?2:-2; System.out.println(x); 5 is less than 0 so 2 is returned and added to -5 and x becomes -3. With that knowledge, what do you think this will print (taken From Tom's closet of Bad Coding Techniques):