Repair subtraction-based comparison

An accounting program orders Balance objects by ascending integer balance in cents. A programmer writes:


Java
public int compareTo(Balance other) {
    return this.cents - other.cents;
}


Object A stores 2000000000 cents, and object B stores -2000000000 cents. Both values fit in a Java signed 32-bit int, whose range is -2147483648 through 2147483647. Integer subtraction wraps on overflow: subtract 4294967296 from an excessively large result, or add 4294967296 to an excessively small result, to obtain its signed 32-bit value.


Find three outputs: the buggy result of A.compareTo(B), the buggy result of B.compareTo(A), and the safe result of Integer.compare(A.cents, B.cents). Enter each as an exact unitless integer with zero decimal places; comparison outputs are not monetary amounts.

Your answers

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

More Comparable Questions: