This week's book giveaway is in the OCMJEA forum. We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line! See this thread for details.
Ashwin Sridhar wrote:Thank you winston. Still i find it strange, why should it widen actually. its more like a IF ELSE block.
Why is the widenig happening depending on the ELSE block datatype
Deep in the bowels of Section 15.25 of the Java Language Specification (portion of the section that explains what type the ternary expression is) ...
Otherwise, if the second and third operands have numeric type, then there are several cases:
If one of the operands is of type byte and the other is of type short, then the type of the conditional expression is short.
If one of the operands is of type T where T is byte, short, or char, and the other operand is a constant expression of type int whose value is representable in type T, then the type of the conditional expression is T.
Otherwise, binary numeric promotion (§5.6.2) is applied to the operand types, and the type of the conditional expression is the promoted type of the second and third operands. Note that binary numeric promotion performs value set conversion (§5.1.8).
This, of course, explains what you are seeing. What it doesn't explain, is why the JLS is written that way ... ?!?
Ashwin Sridhar wrote:its more like a IF ELSE block.
Incorrect. That's an assumption that you are making, but it has nothing to do with the actual definition of that operator. That simplification, like many, is fine in certain contexts, but you have to know its limits and not try to use it beyond those limits.
Jeff Verdegan wrote:
I suppose it's so that the expression could have one consistent type, rather than having its type depend on truth of the condition.
Sorry, I kinda misread the quote (which is bad since I quoted it).... I thought one of them had mentioned a case where it depended on the order (whether 2nd or 3rd operand).
Never mind. We are all good.... and to elaborate the answer, just in case it isn't obvious.
In the first case, zero is a literal, and hence, a compile time constant. It also is representable as a char (the other operand), so, following the second point of the quote, the expression is a char type.
In the second case, following the third point of quote. To get a char and int to be the same type, the char is promoted to an int. So, the expression is an int type.