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
When representing a float data type in Java, we should append the letter f to the end of the data type; otherwise it will save as double. The default value of a float in Java is 0.0f. Float data type is used when you want to save memory and when calculations don't require more than 6 or 7 digits of precision.
A floating-point literal is of type float if it ends with the letter F or f ; otherwise its type is double and it can optionally end with the letter D or d .
Answer. Default data type is Float.
The float covers a range from 1.40129846432481707e-45 to 3.40282346638528860e+38 (positive or negative). Its default value is 0.0f. Its default size is 4 byte.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With