Why do we use `f` for float data types, but not for bytes and short ones?

If we are using a datatype float

in Java, we have to add a f

floating point literal to the end, since Java assumes it is a datatype double

and gives an error, why not do the same for short

and byte

, since both have lower ranges than int

.

+3


source to share


1 answer


You cannot have this thing with byte

, for example, because you byte

can always handle the same thing . It is always a byte. But real numbers can only be represented as approximations. The difference between double

and float

is that it double

uses 64 bits and float

32. Ie The float is less important.

This is similar to int

, and long

for integers. The default type for integers is int

. Likewise, the default type for real numbers is double

.

Now if you want to use precision float

. You need to tell the compiler somehow. That is why it exists f

. To tell the compiler how to handle the value.

Basically, when you do this float x = 0.1f

, you are implicitly casting the literal 0.1

to float.
This statement isfloat x = (float) 0.1

Now try something:



float x = 0.1f;
double y = 0.1;

      

System.out.println(x == y)

will provide you false

. What for? Let's see the first 20 digits after the decimal point:

0.1f --> 1000000014901161200
0.1  --> 1000000000000000055

      

Hope this helps.

+4


source







All Articles