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 2 nd assignment goes through boxing conversion .
While 3 rd assignment goes through widening conversion .
It is because of Java's autoboxing which will convert 1 into an Integer instead of a Double.
Double a = Double.valueOf(1);
should work
The because of auto boxing
Double a = 1; equals to Double a = Integer.valueOf(1);
Double b = 1.0; equals to Double b = Double.valueOf(1);
double c = 1; equals to double c = (double) 1;
What more you can do is to mark your number with D
.
Double d = 1D; equals to Double d = Double.valueOf(1);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.