12

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?

Jan Schultke
  • 17,446
  • 6
  • 47
  • 96
Dávid Natingga
  • 839
  • 3
  • 13
  • 30
  • 1
    Use Float when using Generics, and when you want the float to hold an extra value (null). – Eng.Fouad May 13 '13 at 17:57
  • http://stackoverflow.com/q/12640826/139010 http://stackoverflow.com/q/8419860/139010 – Matt Ball May 13 '13 at 17:57
  • One typical situation is when you want to store your float in a collection: unless it is an array, you have to use Float. – assylias May 13 '13 at 17:58
  • "Generally, you should use primitive types unless you need an object for some reason..." IMHO... – paulsm4 May 13 '13 at 19:06
  • IMHO Neither. There is almost never a good use case for `float`. You are better of using `double` or `Double` or BigDecimal. The memory you save is rarely worth the loss of precision. (double is half a trillion times more precise) You would prefer Float if you have an API which has to have Float. – Peter Lawrey May 13 '13 at 19:22

1 Answers1

8

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.

Woot4Moo
  • 23,987
  • 16
  • 94
  • 151
  • Float.NaN can also represent an unknown value. A `Float` is 5-7x bigger than a `float` – Peter Lawrey May 13 '13 at 19:24
  • @PeterLawrey source on the 5-7x larger – Woot4Moo May 13 '13 at 19:28
  • 8
    float is 4 bytes by definition. A reference needs 4-8 bytes (32/64 bit references). An object header is 12 to 16-bytes (32/64 bit) and must be aligned to 8 bytes. They are not directly comparable as a float alone doesn't use the heap and a Float is on the heap. So in terms of heap usage float: 0, Float is 16-24 bytes. Too many references to dig up ;) – Peter Lawrey May 13 '13 at 19:30
  • 3
    @PeterLawrey today i learned. – Woot4Moo May 14 '13 at 01:21
  • Here's a video from a Google Usergroup Meeting where this specific float vs Float topic is covered in the context of Android's animation framework, mostly regarding Garbage Collection issues https://youtu.be/wJYTBjMZJh0?t=11m20s This is presented by the guy working at Google on the animation framework (Chet Haase) – Daniel F Mar 22 '15 at 14:31