int i = -20; final int j = 20; final int k = i; byte b1 = j; // J in rannge . no cast required byte b2 = (byte) i;// cast req byte b3 = (byte) k;// cast req My question is why is the cast required for b2 eventhough -20 is in the range of byte ?
Talal, You are able to convert j from an int to a byte for two reason. First, it is within the range of a byte. Second, it is a compile-time constant. Just as j is in range for a byte, i is also in range for a byte. However, i is not a compile-time constant. Add the "final" modifier to i and remove the explicit casts as shown below. You will find that the code compiles and runs without error.
Have you tried my mock exam at the URL contained in my signature?
Dan Chisholm<br />SCJP 1.4<br /> <br /><a href="http://www.danchisholm.net/" target="_blank" rel="nofollow">Try my mock exam.</a>