Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Literal Assignment in Java [duplicate]

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?

like image 432
themagiciant95 Avatar asked Sep 29 '16 18:09

themagiciant95


1 Answers

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.

like image 148
Mike Nakis Avatar answered Sep 22 '22 19:09

Mike Nakis