1

Can anyone tell why the auto boxing is not working, and why with constructor it works fine:

int intValue = 12;
Double FirstDoubleValue = new Double(intValue);
Double SecondDoubleValue = intValue; // ==> Error

Thanks for advance :)

Naruto Biju Mode
  • 2,011
  • 3
  • 15
  • 28

2 Answers2

4

The constructor expects a double, a primitive type, in which case, through widening primitive conversion, an int can be used.

However, in

Double SecondDoubleValue = intValue; // ==> Error

you're trying to assign an int to a Double. Those are incompatible types.

Note that boxing conversion

converts expressions of primitive type to corresponding expressions of reference type

so an int would become an Integer, but Integer is still not compatible with Double.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
  • So the auto boxing doesn't use implicitly the wrapper class constructor? – Naruto Biju Mode Mar 26 '14 at 00:42
  • @NarutoBijuMode That's not specified as far as I can tell. As far as I've seen, it typically uses the `static valueOf` method of the corresponding reference type. Note that it still wouldn't make any difference, because it would use `Integer.valueOf(..)`, not `Double.valueOf(..)`. – Sotirios Delimanolis Mar 26 '14 at 00:45
0

Try

Double SecondDoubleValue = (double)intValue;

Java cannot cast int to Double. It can cast int to double, which is what is happening on your second line.

Look here for some in depth answers about conversions. http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html

Matt
  • 71
  • 5
  • I won't down-vote, but I just deleted my answer which stated the same exact thing. He knows how to do it. He's asking why it's necessary. – aliteralmind Mar 26 '14 at 01:52