Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't 'f' necessary when declaring a non-decimal float in Java? [duplicate]

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?
like image 399
Travis Smith Avatar asked Feb 07 '23 16:02

Travis Smith


2 Answers

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
    ...

like image 141
Eran Avatar answered Feb 12 '23 07:02

Eran


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 to long, float, or double
...

enter image description here

like image 28
Andrew Tobilko Avatar answered Feb 12 '23 08:02

Andrew Tobilko