两个操作数分别是 Integer 类型和 Float 类型,根据 [jls-15.25.2](
https://docs.oracle.com/javase/specs/jls/se14/html/jls-15.html#jls-15.25.2 ),条件表达式的结果类型是两个操作数类型提升后的类型:
「 Otherwise, general numeric promotion (§5.6) is applied to the second and third operands, and the type of the conditional expression is the promoted type of the second and third operands.」
根据 [jls-5.6](
https://docs.oracle.com/javase/specs/jls/se14/html/jls-5.html#jls-5.6 ) 描述的类型提升规则:
1. 两个操作数拆包;
2. 拆包后,一个操作数是 int,一个是 float,将 int 扩展为 float
「
1. If any expression is of a reference type, it is subjected to unboxing conversion ( §5.1.8 ).
2. Next, widening primitive conversion ( §5.1.2 ) and narrowing primitive conversion ( §5.1.3 ) are applied to some expressions, according to the following rules:
• If any expression is of type double, then the promoted type is double, and other expressions that are not of type double undergo widening primitive conversion to double.
• Otherwise, if any expression is of type float, then the promoted type is float, and other expressions that are not of type float undergo widening primitive conversion to float.
」
因此这个语句最终的结果是 float 。
---
可以写一段简单的代码看一下这个过程:
❯ cat a.java
class a {
public static void main(String[] args) {
System.out.println(true ? Integer.valueOf(1) : Float.valueOf(3));
}
}
查看它编译后的字节码,可以看到「 10: i2f 」这行确实做了 int -> float 的类型提升:
❯ javap -v a.class
...
public static void main(java.lang.String[]);
descriptor: ([Ljava/lang/String;)V
flags: ACC_PUBLIC, ACC_STATIC
Code:
stack=2, locals=1, args_size=1
0: getstatic #2 // Field java/lang/System.out:Ljava/io/PrintStream;
3: iconst_1
4: invokestatic #3 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
7: invokevirtual #4 // Method java/lang/Integer.intValue:()I
10: i2f
11: invokevirtual #5 // Method java/io/PrintStream.println:(F)V
14: return