Char c = some integer literal can compile, but float f = some floating-point literal will never compile. What for?

char c1 = 123; //Compiles fine char c2 = 123456; //Error: cannot convert from int to char 

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

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

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

PS: I know that floating point literals are considered double by default

+5
source share
1 answer

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

On the other hand, if you assign char int literal within a char type range (e.g. 123), there is no data loss.

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

JLS 5.2 says

Narrowing down a primitive conversion can be used if the type of the variable is a byte, short, or char, and the value of the constant expression is represented in the type of the variable.

+7
source

All Articles