Java: Should I use float or Float?

Dávid Natingga picture Dávid Natingga · May 13, 2013 · Viewed 16.7k times · Source

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?

Answer

Woot4Moo picture Woot4Moo · May 13, 2013

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.