Question

I had been under the assumption, and indeed I believe that I have had experience, that initialising long or float local primitives in Java with raw numbers will generate compiler errors.

E.g.

float f = 10;
long l = 5;

And that the correct way to write the above would be

float f = 10f;
long l = 5l;

Yet I am finding right at this moment the compiler happily compiling without the f and l disclaimers. Am I missing something?

Was it helpful?

Solution

That works fine because you are implicitly performing a widening primitive conversion from int to float and long respectively.

However this would not compile and you would need to add an f or a L to make it work:

float f = 1.0; //can't convert from double to float
long l = 12345678912; //12345678912 is not a valid int

OTHER TIPS

Let's take a look at the "fits into" relation in Java (just the types we're interested in). The graph looks like

                  double
                  /   \
               float  long
                  \   /
                 integer

So, in your case, integers 10 and 5 fit into float, as well as to double, so the implicit conversion does its work and the code compiles fine. However, 10L is of type long, which doesn't fit into int. Same with 2.0, it's double, which can't be assigned to float without explicit cast.

If the integer literal you wrote is convertable to the target data type, it will be done implicit.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top