Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: auto-unboxing combined with casting

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

like image 670
DailyFrankPeter Avatar asked Aug 31 '26 19:08

DailyFrankPeter


2 Answers

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.)

like image 98
Sotirios Delimanolis Avatar answered Sep 02 '26 10:09

Sotirios Delimanolis


Integer has a method shortValue(). Use this instead:

short sPrimitive = iBoxed.shortValue();
like image 26
dkatzel Avatar answered Sep 02 '26 09:09

dkatzel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!