File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Potential Dumb Question....." Watch "Potential Dumb Question....." New topic

Potential Dumb Question.....

David Leland

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

Joined: Jan 07, 1999
Posts: 6920
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 ~ 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

Joined: Jun 19, 2002
Posts: 11
Ah ha!
That makes sense. I never thought to check the precedence of the operator.
I agree. Here's the link:
subject: Potential Dumb Question.....
It's not a secret anymore!