Guard an addition against integer overflow

A Java wallet service stores a balance in cents as an int. The largest int value is 2147483647, and when a sum exceeds it, the result wraps around by subtracting 232=42949672962^{32} = 4294967296. The current balance is 2147000000 cents.


A safe deposit guard is written as if (amount > Integer.MAX_VALUE - balance) reject();. A naive guard is written as if (balance + amount > Integer.MAX_VALUE) reject();. A deposit of 500000 cents arrives.


Find the largest deposit, in whole cents, that the safe guard accepts. Find the value, in cents, that the expression balance + amount actually produces for the 500000-cent deposit. Then state whether the naive guard leaves that deposit accepted or rejected (answer with one word).

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 Defensive Design Questions: