Search code examples
javatypesprimitive

Why can a float be an integer without throwing an exception?


Why does this throw an exception:

float var1 = 24.0;
System.out.print(var1);

But this doesn't:

float var1 = 24;
System.out.print(var1);

I understand that, in the first case, I'd need to include the "f" at the end of the number to distinguish it from a double. But I don't understand why the compiler doesn't have a problem with skipping the "f" if there is no decimal point. I thought that maybe Java was treating it like an int even though I'd declared the variable as a float, but ((Object)var1).getClass().getName() results in 0java.lang.Float.


Solution

  • 24.0 is a double literal, and cannot be automatically (implicitly) converted to a float. 24 is an int literal, so what you see here is a widening primitive conversion from an int to a float.