0

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).

mrbela
  • 4,477
  • 9
  • 44
  • 79
  • Without the "f", the default type of 1.5 is double. – duffymo Dec 04 '18 at 11:55
  • 3
    Hope this SO answer helps https://stackoverflow.com/questions/28361456/why-explicit-type-casting-required-from-double-to-float-but-not-from-int-to-byte – HJK Dec 04 '18 at 11:56
  • By converting from `double` to `float` you are losing accuracy, so the compiler will not do it for you automatically. You need to explicitly tell it that you want a float: `float f = 1.5F;` – rossum Dec 04 '18 at 11:59

0 Answers0