Is this really widening vs autoboxing?

In the first case, you have a widening conversion happening. This can be see when runinng the “javap” utility program (included w/ the JDK), on the compiled class:

public static void main(java.lang.String[]);
  Code:
   0:   iconst_ 5
   1:   istore_ 1
   2:   iload_ 1
   3:   i2l
   4:   invokestatic    #6; //Method hello:(J)V
   7:   return

}

Clearly, you see the I2L, which is the mnemonic for the widening Integer-To-Long bytecode instruction. See reference here.

And in the other case, replacing the “long x” with the object “Long x” signature, you’ll have this code in the main method:

public static void main(java.lang.String[]);
  Code:
   0:   iconst_ 5
   1:   istore_ 1
   2:   iload_ 1
   3:   invokestatic    #6; //Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
   6:   invokestatic    #7; //Method hello:(Ljava/lang/Integer;)V
   9:   return

}

So you see the compiler has created the instruction Integer.valueOf(int), to box the primitive inside the wrapper.

Leave a Comment