Why is the result type of short integer division in Java not a simple integer?
•
Java
Consider this Code:
public class ShortDivision {
public static void main(String[] args) {
short i = 2;
short j = 1;
short k = i/j;
}
}
Compiling this will cause errors
ShortDivision.java:5: possible loss of precision
found : int
required: short
short k = i/j;
Because the type of expression I / J is obviously int, it must be simplified
Why is the type of I / J not short?
Solution
From Java spec:
For binary operations, the small integer type is promoted to int and the result of the operation is int
Editor: why? The simple answer is that Java copied this behavior from c. a longer answer may be related to the fact that all modern machines perform at least 32-bit local computing. Some machines may actually be more difficult to perform 8-bit and 16 bit operations
See: or ing bytes in c# gifts int
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
