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