三元运算符返回意外输出[重复]

问题描述 投票:1回答:1
已经问过这个主题,但我听不懂。您将在下面找到我的程序。当我运行该程序时,它显示X和88。删除int i = 0的声明时,它返回X和X。我在这里找到了一些解释:Unexpected output when using a ternary operator and final variable,但我不太明白。我不明白为什么该程序返回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); } }

java ternary
1个回答
5
投票
请在此处阅读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为字符类型,并且常量表达式为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
© www.soinside.com 2019 - 2024. All rights reserved.