Page 1 of 1

[HD Pg 90, Sec. 3.6.3 - converting-wrapper-objects-to-primitives]

Posted: Tue Jan 08, 2019 8:59 pm
by OCAJO1
A bit beyond the discussion in the section, but I saw this somewhere on the internet and was wondering why would one write such a code just for assigning an int to a float?

Integer integerValue = Integer.valueOf(123);

float floatValue = integerValue.floatValue();
OR
float floatValue = (float)(int)integerValue;

Re: [HD Pg 90, Sec. 3.6.3 - converting-wrapper-objects-to-primitives]

Posted: Tue Jan 08, 2019 9:46 pm
by admin
One use of integerValue.floatValue(); that I can think of is if you have two overloaded methods one taking an int and one a float, and you want to invoke the float version. So, you could do method(integerValue.floatValue()); instead of method(integerValue);

Re: [HD Pg 90, Sec. 3.6.3 - converting-wrapper-objects-to-primitives]

Posted: Wed Jan 09, 2019 1:18 pm
by OCAJO1
Oh that will save a few extra code lines.

As for float floatValue = (float)(int)integerValue; option,

Does doing double casting have any advantages compare to xxxValue(some number).yyyValue() combination?

Thanks

Re: [HD Pg 90, Sec. 3.6.3 - converting-wrapper-objects-to-primitives]

Posted: Wed Jan 09, 2019 11:40 pm
by admin
No, I don't see any advantage. Some may find double casting is less readable.

Re: [HD Pg 90, Sec. 3.6.3 - converting-wrapper-objects-to-primitives]

Posted: Thu Jan 10, 2019 1:06 pm
by OCAJO1
I agree, double casting does look a bit odd :)