-1

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!

aralar
  • 3,022
  • 7
  • 29
  • 44

2 Answers2

2

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 to double.

  • Otherwise, if either operand is of type float, the other is converted to float.

  • Otherwise, if either operand is of type long, the other is converted to long.

  • Otherwise, both operands are converted to type int.

Community
  • 1
  • 1
Makoto
  • 104,088
  • 27
  • 192
  • 230
1

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

Master Slave
  • 27,771
  • 4
  • 57
  • 55