What internally happens at the 3rd line when I execute the following code
Integer i=1;
Double d1=1.1;
Double d2= i+d1;
You can read the definition of "internal" workings in the language spec:
But these might be a bit dry.
Try decompiling the following code:
void add(Integer i, Double d1) {
Double d2= i+d1;
}
This is compiled to:
void add(java.lang.Integer, java.lang.Double);
Code:
0: aload_1
1: invokevirtual #6 // Method java/lang/Integer.intValue:()I
4: i2d
5: aload_2
6: invokevirtual #7 // Method java/lang/Double.doubleValue:()D
9: dadd
10: invokestatic #5 // Method java/lang/Double.valueOf:(D)Ljava/lang/Double;
13: astore_3
14: return
Breaking it down line-by-line (for the significant lines, anyway):
i
from Integer
to int
int
value of i
to double
d1
from Double
to double
double
to Double
.You can see this as being equivalent to:
void add2(Integer i, Double d1) {
Double d2= Double.valueOf((double) i.intValue() + d1.doubleValue());
}
since the two have identical bytecode.
On every arithmetic operation in Java the result is at least int. If any operand is bigger than int the result is the same type of the bigger operand. On the third line, i is unboxed and promoted to double, and added to the unboxed value of d1. Then the result is boxed into d2.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With