Public class Yunsuanfu { publicstaticvoid main (string[] args) { int a = 5; System.out.println ("value is" + ((a<5)?) 10.9:9));} }
Just see an interview problem, the first glance is very simple, a ternary operator, if you think the output of the result is 9, then the problem of the trap, pay attention to "((a<5)? 10.9:9)", There is a 10.9 in it, and the back is followed by a 9, which is the automatic type conversion of Java based on the operator's precision type, because there is a 10.9, so the subsequent 9 will be converted to 9.0, so the output is 9.0.
And look at the other one.
char x= ' x '; int i =10; System.out.println (false ?) i:x); System.out.println (false ?) Ten : x); }
The result of the output is
x
int i=10; I is a variable, so the first output x is cast to int, i is int, the value of x is converted to int value is 120, so the first output is 120.
As for the second output, the Java specification mentions that when the latter two expressions have a constant expression (referred to as 10 above) and the other type is T (referred to as char above), and the constant expression can be represented by T, the output is the T type.
Since 10 is a constant, it can be represented by a char, and the result of the output is a char type, so it is X.
Does it feel like a bit of pit ~ ~
Java ternary operators and type casts