File APIs for Java Developers Manipulate DOC, XLS, PPT, PDF and many others from your application. http://aspose.com/file-tools
Big Moose Saloon
 Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies Register / Login

# ? Operator

Ranch Hand

Joined: Oct 21, 2003
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?

Thanks,<br />Lakshmi.
Jeff Bosch
Ranch Hand

Joined: Jul 30, 2003
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!

Give a man a fish, he'll eat for one day. Teach a man to fish, he'll drink all your beer.
Cheers, Jeff (SCJP 1.4, SCJD in progress, if you can call that progress...)
Ranch Hand

Joined: Oct 21, 2003
Posts: 170
Thank you Jeff....
I missed the fact that assignment operator is right associative.
Thomas Paul
mister krabs
Ranch Hand

Joined: May 05, 2000
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):

Associate Instructor - Hofstra University
Amazon Top 750 reviewer - Blog - Unresolved References - Book Review Blog
Ranch Hand

Joined: Oct 21, 2003
Posts: 170
It should be 2..
qingwu wang
Ranch Hand

Joined: Feb 19, 2003
Posts: 147
a>5?1:2 should be excuted first.the result is 2

Thanks...qingwu<br />When I open my eyes,I see your pretty face.

I agree. Here's the link: http://aspose.com/file-tools

subject: ? Operator