Java: Why do you need to specify an 'f' in a float literal?
There are two floating point types that could be represented as e.g. 100.0
. Only one could be the default. Because of its limited precision, float is an extremely specialized type. The normal case is double, so it is the appropriate default.
On modern processors, float and double have similar compute performance. The only case for using float is large arrays in performance critical situations that require limited precision. Using float doubles the number of floating point values that fit in one cache line. Even then, working out whether float gives enough precision for a given calculation is rarely trivial.
Because otherwise it defaults to double
, which is a more commonly used floating point type than float
.
From the Java Language Specification, section 3.10.2:
A floating-point literal is of type float if it is suffixed with an ASCII letter F or f; otherwise its type is double and it can optionally be suffixed with an ASCII letter D or d (§4.2.3).
(Personally I'd rather there were no default, to make it clear in all cases, but that's a different matter.)
Because unsuffixed floating-point literals are doubles, and rounding means that even small literals can take on different values when rounded to float and double. This can be observed in the following example:
float f = (float) 0.67;
if(f == 0.67)
System.out.print("yes");
else
System.out.print("no");
This will output no
, because 0.67 has a different value when rounded to float than it does when rounded to double. On the other hand:
float f = (float) 0.67;
if(f == 0.67f)
System.out.print("yes");
else
System.out.print("no");
… outputs yes
.
EDIT
Second example:
if(0.67 == 0.67f)
System.out.print("Equal");
else
System.out.print("Not Equal");
… outputs Not Equal
.