There is nothing wrong with
Double j = new Double(5);
because Java will convert 5
from an int
to the double
that a Double
constructor will take. It will also convert the 5
to a double
for the line:
double j =5;
That is a widening primitive conversion.
There is a problem with these lines.
Double j = 5;
Long k =5;
Float g = 5.0;
Java will not perform a widening primitive conversion (5
to 5.0
or 5L
) and a boxing conversion (double
to Double
or long
to Long
) implicitly. It will perform either one implicitly, but not both. It also won't perform a narrowing primitive conversion here (5.0
to 5.0f
).
The JLS, Section 5.2, states:
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.
It doesn't explicitly allow what those last 3 lines are attempting to do: a widening primitive conversion followed by a boxing conversion.
Interestingly, Java does allow:
Number x = 5; // boxing followed by widening
double y = new Integer(5); // unboxing followed by widening