If an 'f' suffix is needed when declaring a float in Java because double is the default value, why is it acceptable to not use the 'f' when the float is a non-decimal?
float myFloat = 123.45 // not ok because double is the default
float myFloat = 123.45f // ok because the float is explicit
float myFloat = 123 // ok, but why? isn't it still a double by default?
The 123
literal is int
by default, not double. There is no problem to assign an int
literal to a float
, since that requires a widening primitive conversion.
When you assign the value of an expression to a variable, the following assignments are allowed :
JLS 5.2. Assignment contexts :
Assignment contexts allow the value of an expression to be assigned (§15.26) to a variable; the type of the expression must be converted to the type of the variable.
Assignment contexts allow the use of one of the following:
an identity conversion (§5.1.1)
a widening primitive conversion (§5.1.2)
...
JLS 5.1.2. Widening primitive Conversion
19 specific conversions on primitive types are called the widening primitive conversions:
byte to short, int, long, float, or double
short to int, long, float, or double
char to int, long, float, or double
int to long, float, or double
...
123
is an int
value that is promoted to float
by default as widening conversion.
int i = 123;
float f = i;
but not vice versa
float f = 123;
int i = f; // <-- the compile-time error
19 specific conversions on primitive types are called the widening primitive conversions:
...
int
tolong
,float
, ordouble
...
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