根据 Java 三元运算符 表达式 ?语句 1 : 语句 2
,
如果 expression
为真则 statement1
将被执行,如果 expression
为假则 statement2
将被执行。
但是当我运行时:
// some unnecessary codes not displaying
char y = 'y';
int i = 0;
System.out.print(false ? i : y);
我期待它打印 y
但它打印 121
,为什么?
编辑
根据 manouti 的回答,编译器解释为 int
,但如果是这样,那为什么我在 i
看到死代码?
如果我执行 System.out.print(false ? 0 : x);
那么我得到 y
,那么为什么在这种情况下编译器不解释作为 int
?
最佳答案
121
是字符 y
的整数表示。由于您提供了 i
作为表达式的一部分,因此编译器将其解释为对 System.out.print(int)
而不是 System.out.print 的调用(字符)
。
请注意,更改为 System.out.print(false ? (char)i : y);
会打印 y
。
关于java - 为什么我的字符打印为数字而不是字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30763489/