Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How java allows to add Integer and Double instance?

Tags:

java

wrapper

What internally happens at the 3rd line when I execute the following code

Integer i=1; 
Double d1=1.1; 
Double d2= i+d1;
like image 312
Palash Bairagi Avatar asked Dec 07 '22 17:12

Palash Bairagi


2 Answers

You can read the definition of "internal" workings in the language spec:

  • Numeric addition
  • Simple Assignment

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):

  • 1: This is unboxing i from Integer to int
  • 4: This is widening the int value of i to double
  • 6: This is unboxing d1 from Double to double
  • 9: This is adding the unboxed (and widened) values.
  • 10: This is boxing the result from 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.

like image 50
Andy Turner Avatar answered Dec 10 '22 05:12

Andy Turner


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.

like image 30
Andres Avatar answered Dec 10 '22 07:12

Andres