Please help me wrap my head around why this doesn't work. (It's not a practical problem, it's a mental excercise for the OCPJP exam.)
public class ImplicitConversions {
Integer iBoxed;
short sPrimitive = (short)iBoxed;
}
//compiler error: incompatible types; required: short, found: Integer
I'm assuming the compiler tries to cast first without (or before) unboxing, whereas for example an arithmetic operation (iBoxed+iBoxed) will unbox it first. Therefore, is it safe to say that auto-boxing/unboxing has its place in the the order of operations (Unary, Arithmetic, Relational, Logical, Conditional, Assignment) and where is it exactly?
I've been reading about casting conversion in source below (to make sure I'm compatible with 1.6), but this one eludes me. Thanks. http://docs.oracle.com/javase/specs/jls/se5.0/html/conversions.html#20232
This
(short)iBoxed
is a stand-alone expression that doesn't depend on its context. What you are trying to do is cast an Integer reference value to a short primitive value. That's just not a casting context that is allowed. (See the table further down in the chapter.)
Integer has a method shortValue(). Use this instead:
short sPrimitive = iBoxed.shortValue();
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