Java Reference
In-Depth Information
< Day Day Up >
Puzzle 8: Dos Equis
This puzzle tests your knowledge of the
conditional operator
, better known as the "question mark
colon operator." What does the following program print?
public class DosEquis {
public static void main(String[] args) {
char x = 'X';
int i = 0;
System.out.print(true ? x : 0);
System.out.print(false ? i : x);
}
}
Solution 8: Dos Equis
The program consists of two variable declarations and two
print
statements. The first
print
statement evaluates the conditional expression
(true ? x : 0)
and prints the result. The result is
the value of the
char
variable
x
, which is
'X'
. The second
print
statement evaluates the
conditional expression
(false ? i : x)
and prints the result. Again the result is the value of
x
,
which is still
'X'
, so the program ought to print
XX
. If you ran the program, however, you found that
it prints
X88
. This behavior seems strange. The first
print
statement prints
X
and the second prints
88
. What accounts for their different behavior?
The answer lies in a dark corner of the specification for the conditional operator [JLS 15.25]. Note
that the types of the second and third operands are different from each other in both of the
conditional expressions:
x
is of type
char
, whereas
0
and
i
are both of type
int
. As mentioned in
the solution to
Puzzle 5
,
mixed-type computation can be confusing. Nowhere is this more
apparent than in conditional expressions
. You might think that the result types of the two
conditional expressions in this program would be identical, as their operand types are identical,
though reversed, but it isn't so.
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.
Search WWH ::
Custom Search