Literal Assignment in Java [duplicate]

落爺英雄遲暮 提交于 2020-01-03 12:25:28

问题


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?


回答1:


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.




回答2:


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;


来源:https://stackoverflow.com/questions/39777836/literal-assignment-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!