Basically, you have to cast an int to a byte almost all the time. The only time you don't have cast an int to a byte is when you're assigning a value to a byte variable and that value is something constant that is within a byte's range - basically if you give it a valid literal value (byte b = 10 ; ) or if you set it equal to a constant with a valid value (final int i = 10; byte b = i ; ). At compile time, the compiler can work out that you're assigning a valid value to the byte and so it doesn't complain. Doing this
int i = 10;
byte b = i;
won't work cos all the compiler will know is that i is a variable with a range much bigger than a byte's. It won't know the value that i will have when you run the program - even though it's obvious to you.
For arithmatic operations,
Java usually promotes all the operands to ints (or bigger) so byte b = i *j; will cause problems even if i and j are bytes and the answer is within a byte's range. However there's one exception to this, and I don't know why, that is the ++ and -- operators. There's no automatic promotion there so
byte b = 1;
b++;
b--;
--b;
++b;
will work fine. However, you still have to be careful. Try
byte b = 127;
b++;
to see what I mean.
Hope this helps,
Kathy
[This message has been edited by Kathy Rogers (edited November 28, 2000).]