Search code examples
javacastingjvmdoubletype-promotion

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


I basically want to debug the following code for Type Promotion to understand the temporary double variable created for x. How can I do this?

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
}}

Solution

  • The answer to your question (as I understand it) is in the Java Language Specification,

    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

    When you use an operator (in this case +) on a pair of operands (x and y) the resulting numeric type is determined by these definitions.

    To add a bit more detail, if you disassemble the classfile generated by your code, the relevant instructions are:

       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
    

    As you can see, x is stored as an int, y is stored as a double. x is pushed onto the stack then converted to a double. After y is pushed onto the stack a dadd (double add) can be performed as both operands are doubles. The javac compiler generates the code that conforms to the Java language spec, as detailed above.