Java: why do you need to specify 'f' in a stream literal?

Why do you need to specify the suffix f in a stream literal?

+32
java floating-point
Dec 31 '13 at 14:47
source share
3 answers

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 a suffix with the letter ASCII F or f; otherwise, its type is double, and it may additionally be a suffix with the letter ASCII D or d (Β§4.2.3).

(Personally, I would prefer that there is no default, that it is clear in all cases, but this is another matter.)

+42
Dec 31 '13 at 14:48
source share

Since unrealized floating point literals are doubled, and rounding means that even small literals can take different values ​​when rounding 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 print no , because 0.67 has a different meaning when rounding to float than when rounding to double. On the other hand:

 float f = (float) 0.67; if(f == 0.67f) System.out.print("yes"); else System.out.print("no"); 

& hellip; outputs yes .

EDIT
Second example:

 if(0.67 == 0.67f) System.out.print("Equal"); else System.out.print("Not Equal"); 
+29
Dec 31 '13 at 14:52
source share

There are two types of floating point that can be represented, for example. 100.0 By default, there can only be one. Due to its limited precision, float is an extremely specialized type. The usual case is double, so it is the default one.

In modern processors, float and double have similar computational performance. The only use cases for float are large arrays in critical situations requiring limited precision. Using float doubles the number of floating point values ​​that correspond to a single cache line. Even then, figuring out whether a float is accurate enough for a given calculation is rarely trivial.

+4
Dec 31 '13 at 15:20
source share



All Articles