what's the difference in defining
double example = 23.1d
or
double example = 23.1
Why long, float and double can end with l, f, d?
what's the difference in defining
double example = 23.1d
or
double example = 23.1
Why long, float and double can end with l, f, d?
There is no difference between double example = 23.1d;
and double example = 23.1;
because a floating point literal without a type suffix is always interpreted as a double.
The type suffixes are necessary in order to avoid ambiguities in certain scenarios.
For example, java supports method overloading. This means that you can have void x( float f );
and void x( double d );
Both methods are called x
; which one will be selected depends on the type that you pass; if you pass a variable which is already known to be either float or double, things are clear; but if you want to pass a literal, like this: x( 5 );
then you have to be able to specify whether you mean this 5 to be a float or a double, so as to select the right method.
There are a few other very nuanced situations where the type of the literal matters. For example, the following code:
System.out.println( "" + (2/3.3333) );
System.out.println( "" + (2/3.3333f) );
Yields the following output:
0.6000060000600006
0.600006
...because the first number is a double, while the second number is a float.
Similar disambiguation concerns make the "L" type suffix necessary for long integer literals.
23.1d (or just 23.1, since double is the default) is a different number than 23.1f. Since 23.1 cannot be exactly represented, 23.1f is the closest float to 23.1, and has only about 6 significant figures. As a double, 23.1 will have about 16 significant figures and can therefore get a bit closer to the actual value.
Note that
double example = 23.1f;
is equivalent to
float f = 23.1f;
double example = (double)f;