Consider this code:
public class ShortDivision {
public static void main(String[] args) {
short i = 2;
short j = 1;
short k = i/j;
}
}
Compiling this produces the error
ShortDivision.java:5: possible loss of precision
found : int
required: short
short k = i/j;
because the type of the expression i/j is apparently int, and hence must be cast to short.
Why is the type of i/j not short?
From the Java spec:
For binary operations, small integer types are promoted to
intand the result of the operation isint.EDIT: Why is it like that? The short answer is that Java copied this behavior from C. A longer answer might have to do with the fact that all modern machines do at least 32-bit native computations, and it might actually be harder for some machines to do 8-bit and 16-bit operations.
See also: OR-ing bytes in C# gives int