4

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?
Travis Smith
  • 622
  • 5
  • 22
  • 1
    http://stackoverflow.com/questions/4097694/float-int-implicit-conversion – Benjamin M Jun 24 '16 at 08:17
  • 1
    Narrowing: double 12345678912344.0 to float, possible loss of near value - not allowed. Widening int 123 to float, float value stays near original value: allowed. – Joop Eggen Jun 24 '16 at 08:28

2 Answers2

5

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

Community
  • 1
  • 1
Eran
  • 387,369
  • 54
  • 702
  • 768
3

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

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142