Can you help me clarify the usages of the float primitive in Java?
My understanding is that converting a float value to double and vice-versa can be problematic. I read (rather long time ago and not sure that it’s actual true anymore with new JVMs) that float’s performance is much worse than double’s. And of course floats have less precision than double.
I also remember that when I worked with AWT and Swing I had some problems with using float or double (like using Point2D.Float or Point2D.Double).
So, I see only 2 advantages of float over double:
-
It needs only 4 bytes while double needs 8 bytes
-
The Java Memory Model (JMM) guarantees that assignment operation is atomic with float variables while it’s not atomic with double’s.
Are there any other cases where float is better then double? Do you use float in your applications?
The reason for including the float type is to some extent historic: it represents a standard IEEE floating point representation from the days when shaving 4 bytes off the size of a floating point number in return for extremely poor precision was a tradeoff worth making.
Nowadays, uses for float are pretty limited. But, for example, having the data type can make it easier to write code that needs interoperability with older systems that do use float.
As far as performance is concerned, I think the float and double are essentially identical except for the performance of divisions. Generally, whichever you use, the processor converts to its internal format, does the calculation, then converts back again, and the actual calculation effectively takes a fixed time. In the case of divisions, on Intel processors at least, as I recall the time taken to do a division is generally one clock cycle per 2 bits of precision, so that whether you use float or double does make a difference.
Unless you really really have a strong reason for using it, in new code, I would generally avoid ‘float’.