Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Should I use float or Float? [duplicate]

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?

like image 233
Dávid Natingga Avatar asked May 13 '13 17:05

Dávid Natingga


People also ask

Should I use float or 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.

Should I use float or double Java?

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.

Are floats faster than doubles Java?

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.

When should we use float in Java?

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.


1 Answers

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.

like image 166
Woot4Moo Avatar answered Sep 23 '22 03:09

Woot4Moo