三元运算符转换整数 [英] Ternary operator casts integer
本文介绍了三元运算符转换整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
请查看以下代码
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?
Can somebody explain me why it is displaying "A" if I made variable 'a'
as a character? And it should display 65 if I made "a"
as a string?
推荐答案
如果其中一个操作数是T类型,其中T是byte,short或char,另一个操作数是一个常量表达式(§15.28)类型为int,其值可在类型T中表示,则条件表达式的类型为T
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,它解释了其他情况下的行为(相同方法)。
Go through the JLS, it explains the behavior (same approach) in other cases.
这篇关于三元运算符转换整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文