I am concerned with dealing with primitive types in Java, especially with the auto conversion.
My question is:
Why does the auto conversion works for byte
and int
, but not for float
and double
?
Take a look at the code:
If I write
byte b = 100;
the compiler first has an int
of value 100
and converts it to a byte
, which fits, because the domain of byte
is [-128, 127]
.
That's why
byte b = 128;
does not work. The compiler says Type mismatch: cannot convert from int to byte
.
But: The same approach to float
and double
it does not work!
If I try
float f = 1.5;
the compiler says: Type mismatch: cannot convert from double to float
, although 1.5
is within the domain of float (float f = 1.5f;
works very fine).