三元运算符 returns 意外输出
Ternary operator returns an unexpected output
这个问题已经有人问过了,但我没听懂。
你会在下面找到我的程序。当我 运行 这个程序打印 X 和 88 时。当我删除 int i = 0 的声明时它 returns X 和 X。我在这里找到了一些解释:Unexpected output when using a ternary operator and final variable 但我没有太不明白了。我不明白为什么这个程序 returns X 和 88 而不是 X 和 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);
}
}
请在此处阅读 ternary operator
的规则
https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.25
第一个是 If one of the operands is of type T where T is byte, short, or char, and the other operand is a constant expression of type int whose value is representable in type T, then the type of the conditional expression is T.
T 的结果,在这种情况下是 char 类型,常量表达式是 0
所以输出是 char 类型,即 x
第二个是 Otherwise, binary numeric promotion is applied to the operand types, and the type of the conditional expression is the promoted type of the second and third operands.
的情况
在此处了解二进制数字提升 https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.6.2
点 2 的最后一种情况适用于此 Otherwise, both operands are converted to type int.
并将 char 转换为 int 给出其 ascii 值,即 88
因此输出为 88
这个问题已经有人问过了,但我没听懂。 你会在下面找到我的程序。当我 运行 这个程序打印 X 和 88 时。当我删除 int i = 0 的声明时它 returns X 和 X。我在这里找到了一些解释:Unexpected output when using a ternary operator and final variable 但我没有太不明白了。我不明白为什么这个程序 returns X 和 88 而不是 X 和 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);
}
}
请在此处阅读 ternary operator
的规则
https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.25
第一个是 If one of the operands is of type T where T is byte, short, or char, and the other operand is a constant expression of type int whose value is representable in type T, then the type of the conditional expression is T.
T 的结果,在这种情况下是 char 类型,常量表达式是 0
所以输出是 char 类型,即 x
第二个是 Otherwise, binary numeric promotion is applied to the operand types, and the type of the conditional expression is the promoted type of the second and third operands.
在此处了解二进制数字提升 https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.6.2
点 2 的最后一种情况适用于此 Otherwise, both operands are converted to type int.
并将 char 转换为 int 给出其 ascii 值,即 88
因此输出为 88