Java Reference
In-Depth Information
The complexity of the rules that determine the result type of a conditional expression
can result in unintended type conversions. Consequently, the second and third operands
of each conditional expression should have identical types. This recommendation also ap-
plies to boxed primitives.
Noncompliant Code Example
In this noncompliant code example, the programmer expects that both print statements
will print the value of alpha as a char :
Click here to view code image
public class Expr {
public static void main(String[] args) {
char alpha = 'A';
int i = 0;
// Other code. Value of i may change
boolean trueExp = true; // Expression that evaluates to true
System.out.print(trueExp ? alpha : 0); // Prints A
System.out.print(trueExp ? alpha : i); // Prints 65
}
}
The first print statement prints A because the compiler applies rule 8 from the result
typedeterminationtabletodeterminethatthesecondandthirdoperandsoftheconditional
expression are, or are converted to, type char . However, the second print statement prints
65 —the value of alpha as an int . The first matching rule from the table is rule 10. Con-
sequently, the compiler promotes the value of alpha to type int .
Compliant Solution
Thiscompliantsolutionusesidenticaltypesforthesecondandthirdoperandsofeachcon-
ditional expression; the explicit casts specify the type expected by the programmer:
Click here to view code image
public class Expr {
public static void main(String[] args) {
char alpha = 'A';
int i = 0;
boolean trueExp = true; // Expression that evaluates to true
System.out.print(trueExp ? alpha : 0); // Prints A
// Deliberate narrowing cast of i; possible truncation OK
Search WWH ::




Custom Search