Reputation: 3773
I don't get why java doesn't do the widening and then autoboxing.
Integer i = (short) 10;
I would think the following would take place:
10
to short
.short
would then widen to int
.int
would then autobox to Integer
.Instead it's a compilation error.
Example 2:
Short x = 10;
Integer y = x;
This fail too.
Upvotes: 4
Views: 1342
Reputation: 1414
Could simulate the similar use case using overloading with respect to autoboxing and widening.
public static void m(short s) {
System.out.println("widening");
}
public static void m(Integer i) {
System.out.println("Autoboxing");
}
public static void main(String[] args) {
short x = 10;
m(x);
}
Output: widening
Hence, in nut shell we could say, Widening dominates Autoboxing in java
Upvotes: 0
Reputation: 1081
IN java it follows sequence as "autoBoxing and then widening" only no matter if you are doing this : int x =5; Object obj = x;
Or this:
int x = 5; Long l = x;
Widening occurs only when there is a is-a relationship.
So while applying above sequence first case is very much valid for compiler, because int would be autobox to Integer and then assigned to Object, i.e. widening (i.e. autobox first and then widening), being in Is-A relationship. But in second case if int x is autbox to Integer and the assign to Long it will not be allowed, being not is-a relationship, hence throws compilation error.
Upvotes: 0
Reputation: 178263
According to the JLS, Section 5.2, which deals with assignment conversion:
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 is unable to apply two conversions at once (widening primitive conversion and boxing conversion); only one conversion can apply here, so it has to result in an error.
The solution would be to cast the short
back to an int
(a casting conversion), which would allow the assignment conversion to be a boxing conversion:
Integer i = (int) (short) 10;
(Or here, don't cast it to short
in the first place.)
Integer i = 10;
Upvotes: 6
Reputation: 44808
What's going on here is a casting conversion from int
to short
, and then an attempted assignment conversion from short
to Integer
.
Assignment conversion (§5.2) allowed for boxing and then widening, but not widening and then boxing.
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.
Upvotes: 3