gpt4 book ai didi

java - 三元运算符强制转换整数

转载 作者:行者123 更新时间:2023-11-29 05:07:04 25 4
gpt4 key购买 nike

请看下面的代码

int a =10;
int b =20;
System.out.println((a>b)?'a':65);//A
System.out.println((a>b)?a:65);//65
System.out.println((a>b)?"a":65);//65

如果我将变量 'a' 作为字符,有人能解释一下为什么它显示“A”吗?如果我将 "a" 作为字符串,它应该显示 65 吗?

最佳答案

此行为记录在 JLS - 15.25. Conditional Operator ? : 中:

If one of the operands is of type T where T is byte, short, or char, and the other operand is a constant expression (§15.28) of type int whose value is representable in type T, then the type of the conditional expression is T

当你写作时

(a > b) ? 'a' : 65

第二种类型转换为 char

通过 JLS,它解释了其他情况下的行为(相同的方法)。

关于java - 三元运算符强制转换整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30023838/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com