Page 1 of 1
OCP 1Z0-815 BOOK Deshmukh, Hanumant - Assigning float to int or double to long and vice-versa
Posted: Sun Feb 02, 2020 10:18 am
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);

Re: Error on OCP 1Z0-815 BOOK Deshmukh, Hanumant
Posted: Sun Feb 02, 2020 11:05 am
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.
Re: Error on OCP 1Z0-815 BOOK Deshmukh, Hanumant
Posted: Sun Feb 02, 2020 11:08 am
by javiut
i understand but which scenarios will a long assigned to a double will lose information?
Re: OCP 1Z0-815 BOOK Deshmukh, Hanumant - Assigning float to int or double to long and vice-versa
Posted: Sun Feb 02, 2020 11:14 am
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.)