If the 2nd and 3rd operands for conditional operator is not in the same type then better to avoid using it. E.g.
char x = 'X';
int i = 0;
System.out.print(true ? x : 0);
System.out.print(false ? i : x);
System.out.print(true ? new Integer(2) : new Float(3));
The specification for the conditional operator [JLS 15.25] has explained this. If both of the operands are not in the same object type then it will convert one of them into the more general one. For an example if operands and Integer and Float objects then it will convert Integer to Float. So as shown is above examples this will cause some unpredictable behaviors.
No comments:
Post a Comment