conditional expression "? :" compiles despite branches returning different types

I've started to learn java and I'm confrunting with the following conditional expression:

 ((1<2)?5:(3<4))

In the book where I've found this example it says that it's a syntax error because it can't convert a numerical value to a boolean one. Same pages after, there is a test with different exercises, including this one.After writing and compiling in eclipse it gives me the output 5. Why? I've read some things about this operator and it clearly says that the both of the expressions must be booleans or arithmetics, so it's a problem with eclipse?

Jon Skeet
people
quotationmark

The conditional operator has three operands - the first is the condition, and the second and third are separate "branches" as it were. Which branch is evaluated depends on whether the condition evaluates to true or false.

In your case, you have:

  • Condition: 1 < 2
  • Branch1: 5
  • Branch2: 3 < 4

Now the problem is that the two branches are of different types here, so there's no useful primitive result type of the expression. It's (surprisingly, IMO) valid, with an overall expression type of Object - basically, both branches involve boxing. So this:

Object o = 1 < 2 ? 5 : 3 < 4;

is equivalent to:

Object o = 1 < 2 ? (Integer) 5 : (Boolean) (3 < 4);

That's specified in JLS 15.25 - your situation is shown in "Table 15.25-B. Conditional expression type (Primitive 3rd operand, Part II)" which shows that when the third operand has a type of boolean and the second has a type of int, the result is lub(Integer,Boolean) - basically Object.

Now this would be fine:

int x = 1 < 2 ? 5 : 4; // Both branches are of type int

And so would this:

// Very confusing with all these conditions, but valid!
boolean y = 1 < 2 ? 5 < 6 : 3 < 4; // Both branches are of type boolean

... but your current situation has one branch of type int, and one of type boolean.

people

See more on this question at Stackoverflow