aspose file tools*
The moose likes Beginning Java and the fly likes Potential Dumb Question..... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Potential Dumb Question....." Watch "Potential Dumb Question....." New topic
Author

Potential Dumb Question.....

David Leland
Greenhorn

Joined: Jun 19, 2002
Posts: 11
Here's the code....

I know from running the code the answer is 1. I'm not sure why it would be 1. I figured it would be 2.
The "if" condition evaluates to true so we run the statement "a=x?1:2". Since x is boolean and a is int, you can't do the assignment, can you?
Frank Carver
Sheriff

Joined: Jan 07, 1999
Posts: 6920
a=x?1:2
This is an example of the "ternary" or "query-colon" operator, which is presumably what this example code is trying to teach or test.
This operator is sort of like an "if", but as an expression not a statement. Imagine it as being equivalent to the following:

Does this help ?


Read about me at frankcarver.me ~ Raspberry Alpha Omega ~ Frank's Punchbarrel Blog
Neil Laurance
Ranch Hand

Joined: Jul 18, 2002
Posts: 183

The ternary operator ( ? : ) has higher precedence than the assignment operator ( = ), so the code above is equivalent to:

And as you know, the ternary operator works like:

Hope this helps, Cheers Neil

[edited hopeless attempts at spelling ternary]
[ July 30, 2002: Message edited by: Neil Laurance ]
[ July 31, 2002: Message edited by: Neil Laurance ]
David Leland
Greenhorn

Joined: Jun 19, 2002
Posts: 11
Ah ha!
That makes sense. I never thought to check the precedence of the operator.
Thanks,
D
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Potential Dumb Question.....