As it states from oracle
Reference from Oracle Docs
Widening Primitive Conversion 19 specific conversions on primitive types are called the widening primitive conversions:
If a float has 32 bits and a long has 64 how is that considered widening? Shouldn't this be considered narrowing?
Widening conversion takes place when two data types are automatically converted. This happens when: The two data types are compatible. When we assign value of a smaller data type to a bigger data type.
A widening primitive conversion does not lose information about the overall magnitude of a numeric value in the following cases, where the numeric value is preserved exactly: from an integral type to another integral type. from byte , short , or char to a floating point type. from int to double.
long to float is a potential loss of precision but not magnitude because the value range for floats is larger than that for longs. So the rule is: Loss of magnitude: explicit cast required; Loss of precision: no cast required.
Well, using scientific notation, we can represent a far wider range of values using fewer bits than if we had not used scientific notation. The largest number a long can hold is 263 - 1. Meanwhile, a float, which is 32 bits shorter than a long, can hold up to (2-2-23)�2127.
The range of values that can be represented by a float
or double
is much larger than the range that can be represented by a long
. Although one might lose significant digits when converting from a long
to a float
, it is still a "widening" operation because the range is wider.
From the Java Language Specification, §5.1.2:
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 (§4.2.4).
Note that a double
can exactly represent every possible int
value.
It is considered widening because the numbers that can be represented by a float is larger than numbers that can represented by long. Just because float uses 32 bit precision does not mean the numbers it can represent are limited to 2^32.
For instance the float (float)Long.MAX_VALUE+(float)Long.MAX_VALUE
is larger than Long.MAX_VALUE
, even though the float has less precision that the long.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With