This week's book giveaway is in the JavaScript forum.We're giving away four copies of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js and have Paul Jensen on-line!See this thread for details.
Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering Languages Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# ? 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):