谁可以解释第一个输出?(Java运算符)

huangapple go评论99阅读模式
英文:

who can explain the first output?(java operator)

问题

运行结果:A
我无法确定第一个输出是A。谁能解释?谢谢!

英文:
public static void main(String[] args) {
        char alpha = 'A';
        int foo = 65;
        boolean trueExp = true;
        System.out.println(trueExp ? alpha : 0);
        System.out.println(trueExp ? alpha : foo);
    }
run result:A
           65

I can’t know the first output is A.who can explian ? thank you!

答案1

得分: 2

来自JLS 15.25.2

如果条件表达式(三元运算符 ? : 的操作数之一)的操作数之一是类型为T,其中Tbyteshortchar,并且另一个操作数是类型为int的常量表达式(§15.29),其值可以表示为类型T,则条件表达式的类型为T

System.out.println(trueExp ? alpha : 0);

alphachar0是具有可以表示为char类型的常量表达式的int,因此条件表达式的结果是char

System.out.println(trueExp ? alpha : foo);

在这里,foo不是常量表达式,因此操作数将进行二进制数值提升为int,因此它打印(int) alpha,即65

如果你声明final int foo,它将再次打印AIdeone演示)。

英文:

From JLS 15.25.2:

> If one of the operands [of the conditional ? : operator] is of type T where T is byte, short, or char, and the other operand is a constant expression (§15.29) of type int whose value is representable in type T, then the type of the conditional expression is T.

System.out.println(trueExp ? alpha : 0);

alpha is a char, 0 is an int with a constant expression which is representable by char, hence the result of the conditional expression is a char.

System.out.println(trueExp ? alpha : foo);

Here, foo is not a constant expression, so the operands will undergo binary numeric promotion to int, hence it prints (int) alpha, 65.

If you were to declare final int foo, it would print A once again (Ideone demo).

huangapple
  • 本文由 发表于 2020年7月29日 16:29:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/63149474.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定