OCP 1Z0-815 BOOK Deshmukh, Hanumant - Assigning float to int or double to long and vice-versa

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

Moderator: admin

Post Reply
javiut
Posts: 37
Joined: Fri Oct 19, 2012 10:48 am
Contact:

OCP 1Z0-815 BOOK Deshmukh, Hanumant - Assigning float to int or double to long and vice-versa

Post by javiut »

I have question on page 59. States code like this.
long value = Long.MAX_VALUE;
final double doubleValue = value;/*LOSE INFORMATION*/

But states that is losing information but why? they both are 64 bits. What information may be lost?

This is returning true.
long value = Long.MAX_VALUE;
double doubleValue = value;
System.out.println(doubleValue==value); :thumbup:

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

Re: Error on OCP 1Z0-815 BOOK Deshmukh, Hanumant

Post by admin »

Actually, the paragraph in the book makes a general point that float and double also lose information when you assign an int or a long to them respectively. And that is correct. Detailed understanding of why this happens is not required for the exam but you may go through this discussion to learn more.

Now, coming to your code. Two things:
1. The text in the book does not claim that information is lost in every assignment. Indeed, once you read about how floating point numbers are stored (not required for the exam), you will realize that information is not lost in every possible assignment. For example, assigning a long containing 0 (zero) to a double will not lose information.

2. Just because == operator returns true does not mean no information is lost. If you print out the value of value and doubleValue, you will see the following output:

Code: Select all

9223372036854775807
9.223372036854776E18
Do you see the difference? They are not exactly the same. Yet, == operator prints true because of numeric promotion (long value gets promoted to double).

HTH,
Paul.

javiut
Posts: 37
Joined: Fri Oct 19, 2012 10:48 am
Contact:

Re: Error on OCP 1Z0-815 BOOK Deshmukh, Hanumant

Post by javiut »

i understand but which scenarios will a long assigned to a double will lose information?

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

Re: OCP 1Z0-815 BOOK Deshmukh, Hanumant - Assigning float to int or double to long and vice-versa

Post by admin »

Information will be lost whenever the number's least significant bits (how many bits? same as the number of the bits used for exponent) are not zeros.
Again, you have to go through the details of how floating point numbers are stored. (Not required for the exam, though.)

Post Reply

Who is online

Users browsing this forum: No registered users and 6 guests