Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 513
Piyush Saravagi Avatar asked Jun 27 '15 19:06

Piyush Saravagi


People also ask

Why do we use F in float?

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.

What is a float literal in Java?

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 .

What is the default data type of floating point literal?

Answer. Default data type is Float.

Is 5f a float in Java?

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.


1 Answers

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.

like image 59
Eran Avatar answered Sep 25 '22 21:09

Eran