Why are Byte.compare() and Integer.compare() implemented differently? Why are Byte.compare() and Integer.compare() implemented differently? java java

Why are Byte.compare() and Integer.compare() implemented differently?


The implementation of Integer.compare does not use subtraction, as this could cause an overflow in case you're comparing an integer that is close to Integer.MIN_VALUE with another that is close to Integer.MAX_VALUE.

This overflow cannot happen in case of Byte.compare, as there the byte values are implicitely converted to integers before x-y is calculated.

(see also: Java Language Specification - 5.6.2 Binary Numeric Promotion)


The Byte method can be implemented this way, becasue the result of the subtraction is representable in int. This is not so in the other case. For example:

0 - 0x80000000 == 0x80000000

and this is negative, hence the comparision would wrongly indicate that 0 is smaller than -2^31