The following line of code is accepted by the compiler (sun-jdk-8u51) without any warnings or errors:
short b = true ? 1 : 1;
Whereas the next two code lines lead to a compilation error (incompatible types: possible lossy conversion from int to short):
boolean bool = true;
short s = bool ? 1 : 1;
Why is the compiler not able to perform the same narrowing conversion of the primitive integer 1 in the second case?
true
is a compile time constant, the whole expression is evaluated during compile time, so you basically haveshort b = 1;
whereas in the second version, the compiler does not do the simplification for you, hence the error. – GustieIf the value of the first operand is true, then the second operand expression is chosen.
For me this sounds pretty inline to the explanation you provided in your first comment and I'd recommend making this an answer to my question. IMO Jon's answer is lacking the influence of the first operand on the ternary operator, on which my question focus. – Bridie