2

If we use float data type in Java we have to add f at the end of floating point literal as Java assumes it to be double data type and gives an error why not do the same for short and byte as both have lower ranges than int.

3
  • Because it doesn't really matter for common values for short and byte. But for precision, float differs from double.
    – Maroun
    Commented Sep 14, 2014 at 9:07
  • Possible duplicate:stackoverflow.com/questions/14102955/…
    – Cratylus
    Commented Sep 14, 2014 at 9:20
  • 1
    Because that's the way they designed it.
    – user207421
    Commented Sep 14, 2014 at 9:59

1 Answer 1

5

You can't have this thing with a byte for example because a byte can always be treated the same. It is allways a byte. But real numbers can only be represented as approximations. The difference between double and float is that double uses 64 bits and float 32. I.e. float is of less percision.

It is a similar thing to the int and long for integers. The default type for integers is int. Similarly the default type for real numbers is double.

Now if you want to use a float precision instead. You need to somehow let the compiler know. That is precisely why the f is there. To tell the compiler how to treat the value.

Basically, when you do this float x = 0.1f you implicitly cast the 0.1 literal to a float.
This statement is equal to float x = (float) 0.1

Now lets try something:

float x = 0.1f;
double y = 0.1;

System.out.println(x == y) will give you false. Why? Lets see the first 20 digits after the decimal point:

0.1f --> 1000000014901161200
0.1  --> 1000000000000000055

I hope this helps.

Not the answer you're looking for? Browse other questions tagged or ask your own question.