4 Replies Latest reply: Sep 30, 2009 9:58 AM by 3004 RSS

    Floating point literals

      Hi, This is a something that when I first started learning java I skimmed over, and now I have a question that is bugging me about floating point literals.

      If all floating point literals in java are automatically a double type then is the reference to a float ignored when the class is compiled?

      I know its probably a stupid question, but the thing that is bugging me is that I always thought the reference was used to allocate memory, if the reference is a float which is 32 bits, but the compiler assumes the type is double which is 64 bits because all floating point literals that are not suffixed are double then what happens with the float declaration? Is it ignored and double used instead?

      I have been googling for an answer and didnt find one that explained what happens, only answers that indicate that double is the default and that I could use a suffix of 'f' if I want the literal to be a float.

      Edited by: PaulOckleford on Sep 30, 2009 12:21 AM
        • 1. Re: Floating point literals
          If all floating point literals in java are automatically a double type
          No, the f postfix makes a literal of the float (and not double) type.
          float a = 1.9f;
          • 2. Re: Floating point literals
            Ok thanks for the answer, it was pretty obvious really! Its still early...

            Can this question be marked as answered?
            • 3. Re: Floating point literals
              You should be able to mark the correct answer yourself, but you need to have mark the thread as question when you created it (I think you didn't).

              Also note that if you assign a float to a double, it gets automatically widened to a double. This can be done because no precision is lost, but it doesn't mean a float-is-actually-a-double.
              float f = 1.0f;
              double d = f; // valid automatically converts float value to double value
              f = d; // error: not allowed since precision would be lost
              f = (float) d; // but can cast explicitly to say that we don't mind the loss
              • 4. Re: Floating point literals
                Also, those aren't references.