Win a copy of Design for the Mind this week in the Design forum!

# ? Operator

Ranch Hand
Posts: 170
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?

Jeff Bosch
Ranch Hand
Posts: 805

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!

Ranch Hand
Posts: 170
Thank you Jeff....
I missed the fact that assignment operator is right associative.

Thomas Paul
mister krabs
Ranch Hand
Posts: 13974
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):