Java Type Promotion 的源代码在哪里以及如何调试它

Where is the source code for Java Type Promotion and how to debug it

我基本上想调试以下用于类型提升的代码,以了解为 x 创建的临时双精度变量。我该怎么做?

public class TypePromotion {
public static void main(String args[]){
    int x = 10;
    double y = 20.0;
    double z = x + y;

    System.out.println("value of Z is :: "+z); // outputs 30.0
    System.out.println("value of X is :: "+x); // outputs 10
}}

你的问题的答案(据我所知)在 Java 语言规范中,

https://docs.oracle.com/javase/specs/jls/se11/html/jls-5.html#jls-5.6.2 https://docs.oracle.com/javase/specs/jls/se11/html/jls-15.html#jls-15.18.2

当您在一对操作数(x 和 y)上使用运算符(在本例中为 +)时,生成的数值类型由这些定义决定。

再补充一点,如果反汇编代码生成的类文件,相关说明是:

   0: bipush        10
   2: istore_1
   3: ldc2_w        #2                  // double 20.0d
   6: dstore_2
   7: iload_1
   8: i2d
   9: dload_2
  10: dadd
  11: dstore        4

如您所见,x 存储为 int,y 存储为 double。 x 被压入堆栈,然后转换为双精度数。在将 y 压入堆栈后,可以执行 dadd(双加),因为两个操作数都是双精度数。 javac 编译器生成符合 Java 语言规范的代码,如上所述。