0

Herbert Schild states in Java A Beginner's Guide:

an automatic type conversion will take place if (a) the two types are compatible and (b) the destination type is larger then the source type

But: He then casts a long into a double so (b) is violated as a 64-bit integer is obviously bigger than a 32-bit type. This is a little confusing and counterintuitive at first.

Shouldn't the condition refined to

the destination type is larger or smaller then the source type given that such a conversion then takes only place if no data is lost as the destination type is sufficiently big enough to hold the data of the source type?

Stuart Marks
  • 127,867
  • 37
  • 205
  • 259
Andrew Tobey
  • 915
  • 3
  • 10
  • 27

3 Answers3

1

Both double and long are 64-bit. However, assigning a 64-bit integer to a double may cause precision loss, which is why an explicit cast is required. Therefore there's no automatic type conversion taking place in this case.

Eran
  • 387,369
  • 54
  • 702
  • 768
1

Actually double is also 64 bits in size.

http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

Rahul T
  • 88
  • 5
0

Such a conversion is called widening conversion which can lead to loss of precision but is allowed.

See the accepted answer for a similar question

Why does Java implicitly (without cast) convert a `long` to a `float`?

http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html

A widening conversion of an int or a long value to float, or of a long value to double, may result in loss of precision - that is, the result may lose some of the least significant bits of the value. In this case, the resulting floating-point value will be a correctly rounded version of the integer value, using IEEE 754 round-to-nearest mode

long: The long data type is a 64-bit two's complement integer. The signed long has a minimum value of -263 and a maximum value of 263-1. In Java SE 8 and later, you can use the long data type to represent an unsigned 64-bit long, which has a minimum value of 0 and a maximum value of 264-1. Use this data type when you need a range of values wider than those provided by int. The Long class also contains methods like compareUnsigned, divideUnsigned etc to support arithmetic operations for unsigned long.

double: The double data type is a double-precision 64-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in the Floating-Point Types, Formats, and Values section of the Java Language Specification. For decimal values, this data type is generally the default choice. As mentioned above, this data type should never be used for precise values, such as currency.

Community
  • 1
  • 1
skgemini
  • 600
  • 4
  • 7