In Java, if we divide byte
s, short
s or int
s, we always get an int
. If one of the operands is long
, we\'ll ge
Whenever you're defining a variable of type byte, whatever you type across from it should be of type byte.
That means it can only be a number in the range of a byte (-128 to 127).
However, when you type in an expression, for ex. byteA/byteB that is not the same as typing in a literal, for ex. the number 127.
This is the nature of Java - the integer is the default data type used for whole numbers.
By default when you're making an assignment of an expression, Java converts that into the default data type (integer) despite the fact that the result of the expression might be a valid value for a byte.
So what happens is that when you define a byte and assign an expression as the value of that byte, Java will need to convert it into an integer:
int byteAByteB = byteA / byteB;
However, you can get around that by casting the assigned expression and thus forsing Java to treat it as a byte.
byte byteAByteB = (byte) (byteA / byteB);
This way you're telling Java to treat that as a byte. (Can also be done with short, etc.)