Page 1 of 1
About Question enthuware.ocajp.i.v8.2.1289 :
Posted: Thu Dec 22, 2016 9:03 pm
by sulakshana
i cant understand this question please explain??????
how it is going to add INTEGER and int....
where it autoboxes and where it unboxes etc....
I need to know how last statement works...///
Re: About Question enthuware.ocajp.i.v8.2.1289 :
Posted: Thu Dec 22, 2016 10:36 pm
by admin
I am not sure what you do mean by "how it is going to add Integer and int". The JVM will unbox both the Integer operands, add them and then assign the result to the int or Integer variable.
In the last statement, since you are assigning the result back to an Integer variable, the result be boxed by the JVM into an Integer object.
HTH,
Paul.
Re: About Question enthuware.ocajp.i.v8.2.1289 :
Posted: Wed Dec 12, 2018 3:43 pm
by OCAJO1
On the same lines as this question,
Short ss = 2;
Integer is = 5;
Long ls = ss + is; //will cause an obvious compiler error.
Long ls = (long) ss + is; //this does not.
I think I've forgotten how casting of one the variable effects the other.
Thanks
Re: About Question enthuware.ocajp.i.v8.2.1289 :
Posted: Wed Dec 12, 2018 8:42 pm
by admin
>Long ls = ss + is; //will cause an obvious compiler error.
If you know the reason for this then you should know the reason for the next one also. It compiles for the same reason!
>Long ls = (long) ss + is; //this does not.
Go through the rules for primitive widening conversion. Also check precedence of cast operator.
Re: About Question enthuware.ocajp.i.v8.2.1289 :
Posted: Wed Dec 12, 2018 9:17 pm
by OCAJO1
Ok after a refresher, lets see if my reasoning for this makes any sense,
For the one that does not compile,
1. both ss and is are unboxed.
2. ss will be widened to int
3. the addition result will be an int
4. the result will be boxed into Integer
5. Integer can not be assigned to Long
For the one that does compile,
1. ss is cast as long so it will be unboxed into short and then widened into long.
2. is will be unboxed to int
3. addition result will be a long
4. the result will be boxed into a Long in order to be assigned to Is
Did I miss anything?
Re: About Question enthuware.ocajp.i.v8.2.1289 :
Posted: Wed Dec 12, 2018 9:22 pm
by admin
Very good
