char c = some integer literal might compile but float f = some floating point literal will never compile. Why?

130 Views Asked by At
char c1 = 123; //Compiles fine
char c2 = 123456; //Error: cannot convert from int to char

Java is smart enough to determine whether an integer is small enough to be converted to a character. Why is it not able to convert very small floating point literals to a float?. For example:

float f1 = 0.3; //Error: cannot convert from double to float
float f2 = 0.3f; //Compiles fine

char c = some integer literal might compile but float f = some floating point literal will never compile. Why?

PS: I know that a floating point literal is treated as a double by default

1

There are 1 best solutions below

5
On BEST ANSWER

0.3 is treated as a double, so its binary representation takes 64 bits and it can't fit into a float without possible loss of precision, so you can't assign it to a float variable without an explicit cast.

On the other hand, if you assign to a char variable an int literal within the range of the char type (for example 123), there's no loss of data.

Both of the assignments (int to char variable and double to float variable) require a narrowing primitive conversion.

JLS 5.2 says

A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable.