Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!

# integers again?!

Sirisha Reddy
Ranch Hand
Posts: 75
int i =10;
byte b = i; --- >Gives an error: cant put int (32 bits) into byte (8bits) - AND thts understandable
long L =10;
float f = L; --->Doesnt throw error ? why??
How can u put a 64 bit long into a 32 bit float??... why doesnt the int-byte logic work here??

Alton Hernandez
Ranch Hand
Posts: 443
Originally posted by Mr. Multeon:
long L =10;
float f = L; --->[b]Doesnt throw error ? why??

This is still considered as promotion. Remember the primitive type heirarchy? So you are still going 'up the chain', so to speak.
A floating point is stored in exponential form. So its accuracy will depend on how many bits are allocated for its mantissa and exponent(I don't know exactly how much for Java)
So assigning long to float is still OK. It will just convert it to its exponential form. However, this does not guarantee that it can preserve the original value. Precision may still be lost.

Marlene Miller
Ranch Hand
Posts: 1392
Here is a program that finds the first long that cannot be represented exactly as a float.

1 0000 0000 0000 0000 0000 0001
A float has 23 bits for the fraction part. This number needs 24 bits.

Marlene Miller
Ranch Hand
Posts: 1392
A 32-bit floating point number looks like this
1 bit for the sign
8 bits for the exponent (unsigned 0-255)
23 bits for the signficand (fraction)
The way you convert a long to a float is
1. Write the long as a binary number
2. Write the number in normalized form 1.xxxxxxxxxxx
3. Since the most significant digit will always be 1, drop that digit.
4. Put the most significant 23 digits into the significand
5. Compute the exponent and add 127
(2^-1 -> 126, 2^0 -> 127, 2^1 -> 128)
[ June 12, 2003: Message edited by: Marlene Miller ]

Yi Meng
Ranch Hand
Posts: 270

Sirisha Reddy
Ranch Hand
Posts: 75
Thank you miller.

Marlene Miller
Ranch Hand
Posts: 1392
This is not needed for the exam.
Here is an example of the format of a floating point number.

1000111000110000111011000000000 (only 31 bits here, count 'em)
0 10001110 001 1000 0111 0110 0000 0000
The sign is 0. It�s a positive number.
The exponent is 128+14. Subtract 127. The real exponent is 15.
The signficand is 001 1000 0111 0110 0000 0000