java - 从 Java 程序获得意外输出时的困惑

标签 java

<分区>

public static void main(String[] args) {
  Object o=true?new Integer(1):new Double(1.0);
  System.out.println(o);
 }

我得到 1.0 作为输出,首先是上面的 else 语句无法访问,但它是如何自动类型转换的。

最佳答案

JLS 指出

Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules: • If either operand is of type double, the other is converted to double.

在表达式中

true? Integer(1) : Double(1.0)

因为这里的操作数之一是 Double,所以返回类型也是 double

关于java - 从 Java 程序获得意外输出时的困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19311246/

相关文章:

java - jaxb2-maven-plugin:无法从 WSDL 生成源

java - applet 可以与 servlet 实例通信吗

java - 将未知类型泛型列表转换为数组

java - CoreNlp 拆分 stanford-corenlp-3.2.0-models.jar

java - TableLayout 中的 TextView 数组

java - 当单击按钮时,我调用了一个构造函数,在 android 中显示类转换异常

java - Android Volley Request中出现网络或超时错误时如何再次调用API

java - Install4j 输入验证表达式

java - 边界框中的 itext 多行文本

java - 单选按钮操作监听器中的问题