x - y
is presumably the most efficient (since the alternative involves branching twice), so that's used for short
.
But x - y
can't be used for int
or long
, because this will overflow when the resulting value doesn't fit in an int
, which can give a positive value when the result should be negative, or a negative value when the result should be positive (or zero in either case).
Note: when subtracting two short
s, the resulting value is of type int
, so that can never overflow.
// long - long
System.out.println((int)(2147483649l - 1l)); // -2147483648, not 2147483648
// int - int
System.out.println(-2147483648 - 1); // 2147483647, not -2147483649
// int - int
System.out.println(1 - -2147483648); // -2147483647, not 2147483649
// short - short
short s1 = -32768, s2 = 1;
System.out.println(s1 - s2); // -32769, as desired
For what it's worth: the values above were chosen since they're roughly around the minimum and maximum values for int
(and short
), to demonstrate at which point it overflows.