Originally posted by Paul Salerno:
a while back we had discussed the fact that this statement does not need casting:
Case 1:
int i = 100
byte b = i // i is a constant and fits into byte
No, this will give you an error! You can do this though:
byte b = 100;
Case 2:
int i = 12
byte b = i // is this legal?
No. I think you're confusing literals and variables. The compiler has no clue what the current value in a variable is when you compile it, so it won't let you make narrowing assignments without an explicit cast. However, if the compiler can tell
at compile time what the value is, as with literals and static final variables, then it will allow implicit narrowing assignments provided the value actually fits in the variable.
Case 3:
final char c = 10
byte b = c // is this legal?
Yes. The value in c cannot change, and the compiler can tell what the value is at compile time, so it will allow this.
Case 4:
final short s = 5
byte b = s // is this legal?
Yes, for same reason as above.