40

I am studying the source of the OpenJDK.

My attention was attracted by the methods Byte.compare() and Integer.compare():

public static int Byte.compare(byte x, byte y) {
    return x-y;
}

public static int Integer.compare(int x, int y) {
    return (x < y) ? -1 : ((x == y) ? 0 : 1);
}

Why do the methods Byte.compare() and Integer.compare() have different implementations?

Sergey Morozov
  • 4,528
  • 3
  • 25
  • 39

2 Answers2

50

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)

isnot2bad
  • 24,105
  • 2
  • 29
  • 50
8

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

Ingo
  • 36,037
  • 5
  • 53
  • 100