Search code examples
javatype-conversionprimitive

The error in example of Java Specification?


There are two main kinds of primitive conversion:

  • widening conversion;
  • narrowing conversion.

I'm reading about widening conversion in Java SE Specification and here I'm seeing the following picture:

enter image description here

int big = 1234567890;
float approx = big; // good, it's widening conversion (int -> float)
System.out.println(big - (int)approx); // what? (float -> int)

In last line of code, I think it's narrowing conversion, am I right? If I'm wrong, explain me please! Thanks in advance.


Solution

  • Yes, the last line uses a narrowing conversion, which is why a cast is necessary. The example is used to demonstrate that the widening conversion on the middle line loses information, that's all:

    This program prints -46 thus indicating that information was lost during the conversion from type int to type float because values of type float are not precise to nine significant digits.