• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

? Operator

 
Lakshmi Saradha
Ranch Hand
Posts: 170
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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!
 
Lakshmi Saradha
Ranch Hand
Posts: 170
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Jeff....
I missed the fact that assignment operator is right associative.
 
Thomas Paul
mister krabs
Ranch Hand
Posts: 13974
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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):
 
Lakshmi Saradha
Ranch Hand
Posts: 170
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It should be 2..
 
qingwu wang
Ranch Hand
Posts: 147
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
a>5?1:2 should be excuted first.the result is 2
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic