As per the Java ternary operator expression ? statement1 : statement2
,
if expression
is true then statement1
will be executed, if expression
is false then statement2
will be executed.
But when I run:
// some unnecessary codes not displaying
char y = 'y';
int i = 0;
System.out.print(false ? i : y);
I am expecting it to print y
but its printing 121
, why?
EDIT
As per the manouti answer, the compiler interprets as int
, but if that is the case then why I am seeing dead code at i
?
If I do System.out.print(false ? 0 : x);
then I am getting y
, so why in this case doesn't the compiler interpret as int
?
The short answer to your question is that the value printed is based on the type that the conditional expression evaluates to.
So really your question boils down to, why does the type of the conditional expression differ between
and
To answer that, we'll need to take a look at section §15.25 of the Java Language Specification.
There are three types of conditional expression in Java:
Since both
int
andchar
are convertible to a numeric type, the expression is an example of a numeric conditional expression according to this rule:Given that, the rule for determining the type of the entire expression is given as follows:
Notice that the fourth rule exactly describes the second example; the second operand is constant of type
int
(0
) and the third is achar
, so the conditional expression will evaluate tochar
. This will cause the compiler to use theprint(char)
method, which will printy
.However when you instead pass in a variable instead of a constant, you fall down to the last rule which says that "...the type of the conditional expression is the promoted type of the second and third operands."
If you take a look at section §5.6.2 of the JLS, it describes the rules for type promotion as follows:
By following these rules, the type of the expression will be
int
, and so the compiler will use theprint(int)
method, which will print121
(the ascii value ofy
).