My colleague told me that I should use float
whenever possible to reduce the object creation and increase the performance. Java silently converts float
to Float
(this needs some computational power) whenever necessary. So it seems to me that the only need for Float
is when one needs to use the object Float
very often instead of its primitive.
When looking at java.awt.Color
, it is using the Float
, perhaps unnecessarily.
When would one need to prefer Float
over float
in Java?
When would one need to prefer Float over float in Java? Use Float when using Generics, and when you want the float to hold an extra value (null). One typical situation is when you want to store your float in a collection: unless it is an array, you have to use Float.
You should use double instead of float for precise calculations, and float instead of double when using less accurate calculations. Float contains only decimal numbers, but double contains an IEEE754 double-precision floating point number, making it easier to contain and computate numbers more accurately.
Performance-wise there's not likely to be much difference, and double may actually be faster. If Java is being run on a processor that doesn't have a floating-point unit at all, or supports 32-bit floats but not 64-bit floats, then a float could be faster.
Float data type is used when you want to save memory and when calculations don't require more than 6 or 7 digits of precision.
The object Float
can be set to null to represent a value that is unknown.
The primitive float
is guaranteed to have a value.
There is some overhead on the autoboxing, but this is negligible. You still must allocate space for the primitive so there is nothing you gain there.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With