Java: Should I use float or Float?
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.
Dávid Natingga
2010 - 2014, Imperial College London, MEng Computing (Artificial Intelligence) 2014 - 2019, University of Leeds, a PhD candidate in Computability Theory Check my free Android app Sophia Number Guesser that will guess the hidden digit in your number!
Updated on June 05, 2022Comments
-
Dávid Natingga almost 2 years
My colleague told me that I should use
float
whenever possible to reduce the object creation and increase the performance. Java silently convertsfloat
toFloat
(this needs some computational power) whenever necessary. So it seems to me that the only need forFloat
is when one needs to use the objectFloat
very often instead of its primitive.When looking at
java.awt.Color
, it is using theFloat
, perhaps unnecessarily.When would one need to prefer
Float
overfloat
in Java?