Alex Rivera | Logout

For what purpose does java have a float primitive type?

Asked 2010-04-28T22:14:47.653
25

Can you help me clarify the usages of the float primitive in Java?

My understanding is that converting a float value to double and vice-versa can be problematic. I read (rather long time ago and not sure that it's actual true anymore with new JVMs) that float's performance is much worse than double's. And of course floats have less precision than double.

I also remember that when I worked with AWT and Swing I had some problems with using float or double (like using Point2D.Float or Point2D.Double).

So, I see only 2 advantages of float over double:

  1. It needs only 4 bytes while double needs 8 bytes

  2. The Java Memory Model (JMM) guarantees that assignment operation is atomic with float variables while it's not atomic with double's.

Are there any other cases where float is better then double? Do you use float in your applications?

Edit
Report

1 Answer

3

So yes, advantages of floats:

  1. Only requires 4 bytes
  2. Atomic assignment
  3. Arithmetic should be faster, especially on 32bit architectures, since there are specific float byte codes.

Ways to mitigate these when using doubles:

  1. Buy more RAM, it's really cheap.
  2. Use volatile doubles if you need atomic assignment.
  3. Do tests, verify the performance of each, if one really is faster there isn't a lot you can do about it.

Someone else mentioned that this is similar to the short vs int argument, but it is not. All integer types (including boolean) except long are stored as 4 byte integers in the Java memory model unless stored in an array.

answered 2010-04-28T22:35:18.740

Your Answer