This subject is already asked but I didn't understand it. You'll find my program below. When I run this program it prints X and 88. When I remove do the declaration of int i = 0 it returns X and X. I found some explanations here : Unexpected output when using a ternary operator and final variable but i didn't understand it so much. I don't understand why this program returns X and 88 instead of X and X.
public class Ternary {
public static void main(String[] args) {
char x = 'X';
int i = 0;
System.out.println(true ? x : 0);
System.out.println(false ? i : x);
}
}
该声明
可以写成
which will print
X
同样,声明
可以写成
which will print
X
Thus, the output is
X
andX
.Both paths through the ternary must be of the same type.
char
can (and is) widened to anint
yielding the ascii value88
instead ofX
.而且两者都将输出