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
.
1 Answer
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.
short
andbyte
. But for precision,float
differs fromdouble
.