Tuesday 17 January 2012

Conditional Operator with different operand types

Lets have a look at this program:
char x = ’X’;
int i = 0;
System.out.print(true ? x : 0);
System.out.print(false ? i : x);

Expected output is XX, but output printed is X88....can you guess why??????

The reason for this is mixing 2 different types of operands...here char and int.

So lets first see, how conditional operator works in java, see JLS 15.25
The rules for determining the result type of a conditional expression are too long and complex to reproduce in their entirety, but here are three key points.
1. If the second and third operands have the same type, that is the type of the conditional expression. In other words, you can avoid the whole mess by steering clear of mixed-type computation.
2. 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, the type of the conditional expression is T.
3. Otherwise, binary numeric promotion is applied to the operand types, and the type of the conditional expression is the promoted type of the second and third operands.

So now lets see the first expression:

System.out.print(true ? x : 0);
Here first operand is char, and second operand is constant so 2nd point will apply...so type will remain T..i.e. char...so right output is printed.

Consider the second case:

System.out.print(false ? i : x);
Here first operand is integer variable and second operand is character, so argument 3 will hold....so char is promoted to int and ascii value of char is printed.

Making it print XX will only take to make i as final.
final int i = 0;


No comments:

Post a Comment