As far as I know, to convert an integer to a double one can multiply the former by "1.0". It's apparently also possible to add "1d" (the double literal) to it. What, then, is the difference?
Thanks!
As far as I know, to convert an integer to a double one can multiply the former by "1.0". It's apparently also possible to add "1d" (the double literal) to it. What, then, is the difference?
Thanks!
So, if you mean "add the d
to the end of the numeral"...then there's no difference. In Java, by default, all floating-point literals are double
.
So these two literals are the same thing:
41.32
41.32d
If you were to add f
instead of d
, then one would be a float
instead of a double
.
You can change an int
to a double
in this way, too:
113
113d
If you're multiplying an int
with a double
to get a double
, then the int
is being promoted to a double
so that the floating-point arithmetic can take place.
From the JLS:
Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules:
If either operand is of type
double
, the other is converted todouble
.Otherwise, if either operand is of type
float
, the other is converted tofloat
.Otherwise, if either operand is of type
long
, the other is converted tolong
.Otherwise, both operands are converted to type
int
.
Adding 'd' is like an explicit cast to a double, multiplying will also convert to double cause
If either operand is of type double, the other is converted to double before the operation is carried out.
and 1.0 is a double, so multiplying an int by 1.0, would give a result of type double, but would also convert the other operand to double