Java如何确定三元条件运算符表达式的类型? [英] How does Java decide the type of a ternary conditional operator expression?
问题描述
有人可以解释吗?
public class Test {
public static void main(String[] args) {
char c = 'A';
int i = 0;
boolean b = true;
System.out.println(b ? c : i);
System.out.println(b ? c : (char)i);
System.out.println(b ? c : 0);
System.out.println(b ? c : (char)0);
}
}
输出:
65
A
A
A
65
A
A
A
从我的站立位置看,这看起来确实很奇怪。我希望只打印 A
s。而且:当我用 0
代替 i
时,输出会改变吗?对于所有 i
值,输出似乎是相同的,而不仅仅是 0
。
It sure looks strange from where I'm standing. I would have expected only A
s to print out. And moreover: how come when I substitute 0
for i
the output changes? The output seems to be the same for all values of i
, not just 0
.
推荐答案
从Java语言规范开始,有关类型转换和升级(请参见粗体文本)
From the Java Language Specification, about type conversion and promotion (see the text in bold)
使用Java编程语言编写的每个表达式的类型都可以从表达式的结构和文字类型,
变量以及在其中提到的方法中推导出
。表达方式。但是,可能
在表达式类型不合适的上下文中编写表达式。
在某些情况下,这会在编译时导致错误。在其他情况下,上下文
能够接受与表达式类型相关的类型; 为方便起见,
Java编程语言执行了
而不是要求程序员明确地指示类型转换,而是从
表达式的类型执行隐式转换,以将其转换为可接受的类型。
在您的情况下,在编译时发生的类型转换将解释输出。
The type conversion in your case that happens at compile time explains the output.
在涉及 i
的情况下, c
已被提升为
In the cases where i
was involved, c
has been promoted to integer.
在涉及到 0
的情况下,它被视为字符,因此 c
仍然是字符。
In the cases where 0
was involved, it is treated as character and hence c
remained as character.
这篇关于Java如何确定三元条件运算符表达式的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!