My code goes like this --
public void abc{
long a=1111;
float b=a; // this works fine even though this is narrowing conversion
long c=b;// this gives compilation error
}
Can you explain why this is happening?
The reason is specified in JLS 5.1.2:
It says that : long to float or double is a widening conversion.
Whereas, float to byte, short, char, int, or long is narrowing conversion.
That's why float b=a;
is working fine in your program , since it is widening conversion.
And
long c=b;
is showing compilation error since it is a narrowing conversion.
When you convert from an integral type to a floating point one, it is always clear what you want to do: you change number's representation, but you keep the same number.
Converting from floating point to integral types, on the other hand, has some ambiguity: it is not clear what you would like to do with the fractional part. You may want to
That's why the language asks you to be specific about what you want to do when converting floating-point numbers to integral types.
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