Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Potential Dumb Question.....

 
David Leland
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 6920
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ?
 
Neil Laurance
Ranch Hand
Posts: 183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ah ha!
That makes sense. I never thought to check the precedence of the operator.
Thanks,
D
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic