Look at the three lines of code below.
float f = 1;
float g = 1.1;
float h = 1.1f;
Second line has compilation errors, while the other lines do not have compilation errors. First line is working fine without suffix f and third line is working with suffix f. Why is this?
Floating point literals in Java is a
doublevalue by default.You can’t assign a
doublevalue to afloatwithout an explicit narrowing conversion. You therefore have two options:forFto denote afloatvalue(float)An example of the latter is:
On widening conversions
The reason why this compiles:
is because the widening conversion from
inttofloatcan be done implicitly in the context of an assignment.Other data type suffix for literals
As mentioned above, there’s also the
Dordsuffix fordouble. Consider this snippet for example:There’s also a suffix for
longliterals, which isLorl(lowercase letter). It is highly recommended that you use the uppercase variant.