英文:
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
,其中T
为byte
、short
或char
,并且另一个操作数是类型为int
的常量表达式(§15.29),其值可以表示为类型T
,则条件表达式的类型为T
。
System.out.println(trueExp ? alpha : 0);
alpha
是char
,0
是具有可以表示为char
类型的常量表达式的int
,因此条件表达式的结果是char
。
System.out.println(trueExp ? alpha : foo);
在这里,foo
不是常量表达式,因此操作数将进行二进制数值提升为int
,因此它打印(int) alpha
,即65
。
如果你声明final int foo
,它将再次打印A
(Ideone演示)。
英文:
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).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论