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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top