Why do I get an error when attempting to initialize a Double
to an int
, even though it does not throw an exception when using the primitive type, double
?
Double a = 1; // error - incompatible types
Double b = 1.0; // OK
double c = 1; // OK
Why is the behavior different between the class Double
and the primitive type, double
?
When you initialize your Double
as:
Double a = 1;
There needs to be done 2 things:
int
to Integer
Integer
to Double
Athough, boxing is fine, but widening from Integer
to Double
isn't valid. So, it fails to compile.
Note that, Java doesn't support Widening followed by Boxing conversion, as specified in JLS §5.2:
Assignment contexts allow the use of one of the following:
- an identity conversion (§5.1.1)
- a widening primitive conversion (§5.1.2)
- a widening reference conversion (§5.1.5)
- a boxing conversion (§5.1.7) optionally followed by a widening reference conversion
- an unboxing conversion (§5.1.8) optionally followed by a widening primitive conversion.
Your 2nd assignment goes through boxing conversion.
While 3rd assignment goes through widening conversion.
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