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

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
OCAJO1
Posts: 221
Joined: Mon Nov 26, 2018 2:43 pm
Contact:

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

Post 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;

admin
Site Admin
Posts: 10046
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

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

Post 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);
If you like our products and services, please help us by posting your review here.

OCAJO1
Posts: 221
Joined: Mon Nov 26, 2018 2:43 pm
Contact:

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

Post 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

admin
Site Admin
Posts: 10046
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

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

Post by admin »

No, I don't see any advantage. Some may find double casting is less readable.
If you like our products and services, please help us by posting your review here.

OCAJO1
Posts: 221
Joined: Mon Nov 26, 2018 2:43 pm
Contact:

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

Post by OCAJO1 »

I agree, double casting does look a bit odd :)

Post Reply

Who is online

Users browsing this forum: Bing [Bot] and 66 guests