With the comments it is clear that there is a confusion between boxing and casting . They are completely different concepts.
Boxing
What the Double
type does is boxing of floating point values with double precision. He does not convert, does not promote anything. It takes this value and places it inside a class called Double
.
This class is a type by reference, so the variable that will contain the value has a pointer to the object where the data is. The stored value is there in the object and can only be accessed indirectly through the pointer. The compiler already does this by the programmer.
This is called boxing a value on an object. There is no conversion here.
Casting
Casting is a promotion process from one type to another. In some cases it is only to indicate to the compiler that the value should be interpreted as if it were another. In another it is necessary to make a conversion, since its internal structure is different. When it is possible to do it safely the compiler automatically applies casting in some situations pre-established by the language.
I mentioned this in What is upcasting and downcasting in the Java language? .
This is because there are rules in the language of self-promotion of compatible types only between the primitive types of the language. It works:
double d1 = 10;
double
is a primitive type. Double
is not, this is already known. So in the use of the class there is no promotion of an integer for Double
. There is no rule that determines what should be done.
They could have defined it in the language, but they did not and it even makes sense not to do it in the language itself. If they had, you could have an cast operator implicit in the Double
class. This, of course, would allow Java to have the definition of operators in classes.
cast explicit , then all ok:
Double d2 = (double)10;
You can pass a value that already is a double
through literals:
Double d3 = 10.0;
Double d4 = 10d;
Or through a constructor or other method (used in the question) to create a double-precision number:
Double d5 = new Double(10);
Note that the constructor expects a double
and the integer promotion for this type occurs implicitly according to the language specification.
See running on ideone and on CodingGround .
Boxing for Double
expects a number of type double
to box it, if it does not get exactly that, it does not work.
By the comments it seems difficult to understand this, then I will repeat: There is no rule that determines this automatic conversion, it only works if it is explicit.
It would be enough to have rules that would determine that this was done by the compiler that would work. The language developers thought it was not desirable, probably because they thought it might happen by accident.