Why is "f" not required when declaring a non-decimal float in Java?

If the suffix 'f' is needed when declaring a float in Java, because double is the default, why is it acceptable not to use 'f' when the float is not 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?
+4
source share
2 answers

A literal 123has a intdefault value , not a double. There is no need to assign a literal intto float, since this requires an extension of the primitive transform.

When you assign an expression value to a variable, the following assignments are allowed:

JLS 5.2. :

(§15.26) ; .

:

  • (§5.1.1)

  • (§ 5.1.1)
    ...

JLS 5.1.2.

19 :

  • byte , int, long, float double

  • short int, long, float double

  • char int, long, float double

  • int ,
    ...

+5

123 - int, float .

int i = 123;
float f = i;

float f = 123;
int i = f; // <-- the compile-time error

19 :

...
int long, float double
...

enter image description here

+3

All Articles