How long to float is implicit conversion in Java?
Those who are Java programmers may already know that the casting between long to float is implicit by nature in Java. But do you people ever thought about how it is made possible?
Why will we ponder on this?
Just because long takes 8 bytes and float is only 4 bytes. How Java accommodates this 8 bytes stuff into 4 bytes? There will be loss of data. Isn’t it?
Here is a simple answer
You can find in a standard text book. The text is as follow:
Conversion from long (8 bytes) to float (4 bytes) is implicit because float save values in the form of exponents
Many people find it confusing and I got this question asked by 4 of my friends Most of you might know the internal working but for those who don’t I am trying to explain you.
Float store values in the form of exponents which means 2345678 will be stored as 2.345678E6, where E6 stands for 10 to the power of 6
So when we store a long value which ofcourse cannot be stored in a float, JVM converts it into exponential form and then stores it. Say, if we want to store a long value of 1234567891234 in a float, then it will first be converted into an exponential form like this: 1.234567891234E12 and hence this made it possible to store the value in a float variable which is really done implicitly.
Hold on !
There are still few things that you may have noticed. What about the precision? A Float has precision of 6-7 significant digits after decimal? I am still loosing data.
Here comes one more concept from data storage:
The JVM doesn’t cares about loss of precision. It only cares about loss of magnitude. In the above example, 1 is magnitude and the digits after the decimal is the precision.