This may sound too trivial for an intermediate Java programmer. But during my process of reviewing Java fundamentals, found a question:
Why is narrowing conversion like:
byte b = 13;
will be allowed while
int i = 13;
byte b = i;
will be complained by the compiler?
Because
byte b = 13 ;is assignment of a constant. Its value is known at compile time, so the compiler can/should/will whine if assignment of the constant’s value would result in overflow (trybyte b = 123456789 ;and see what happens.)Once you assign it to a variable, you’re assigning the value of an expression, which, while it may well be invariant, the compiler doesn’t know that. That expression might result in overflow and so the compiler whines.