Prerequisites and problem
A counter can start within the long range and still overflow after several valid-looking changes. This JDK 21 example calculates a complete candidate total using checked addition, then assigns the result only if every step succeeds. It uses no dependencies, files or external services. Save the class in a file matching its public class name.
Use this pattern when the application contract says that every intermediate total must fit in a signed 64-bit integer. The contract matters: a sequence that temporarily exceeds the range and later returns inside it is rejected here. If only the final mathematical sum needs to fit, accumulate using BigInteger and perform an exact conversion at the end instead.
Checked arithmetic and assignment
Math.addExact throws ArithmeticException when an addition cannot be represented in the chosen primitive type. The sample uses the long overload because candidate and change are both long. Ordinary addition would allow wraparound, potentially turning a large positive count into a negative value without providing a useful failure signal.
The stored variable receives the method result through a single assignment. Java evaluates the method call before performing that assignment. If a later addition throws, the right-hand side never completes and the original stored value remains available. The local candidate may have advanced through earlier changes, but it is not published outside the method.
Boundary tests and limitations
The sample tests an ordinary mixed-sign total, the exact maximum and minimum boundaries, positive overflow and negative underflow. The positive overflow occurs after one successful intermediate addition. That verifies the point of using a local candidate: the caller does not retain a partially updated result when a later change fails.
This guarantee applies to the local variable and pure method shown. It does not make a database update transactional or protect a shared field from concurrent writers. If another thread can change the starting value while you compute, use the concurrency mechanism appropriate to that state. Keep external writes outside the calculation or place them in a real transaction.
Troubleshooting
If an overflow check appears ineffective, inspect arithmetic that happens before the checked method call. For example, multiplying two int values to construct a change can already wrap before that change reaches this function. Widen operands at the correct point and use multiplyExact when multiplication also needs a checked boundary.
Do not catch ArithmeticException and return zero as though zero were a successful aggregate. Translate the error into an explicit failed update or a validation message. The small check helper throws AssertionError directly, so these tests do not depend on enabling Java assertions with -ea. The example was compiled and run on JDK 21, including the boundary failures.
Complete example
Save as ExactTotal.java.
public class ExactTotal {
static long total(long starting, long... changes) {
long candidate = starting;
for (long change : changes) {
candidate = Math.addExact(candidate, change);
}
return candidate;
}
static void check(boolean condition) {
if (!condition) throw new AssertionError("check failed");
}
public static void main(String[] args) {
check(total(10, 20, -5) == 25);
check(total(Long.MAX_VALUE - 1, 1) == Long.MAX_VALUE);
check(total(Long.MIN_VALUE + 1, -1) == Long.MIN_VALUE);
long stored = Long.MAX_VALUE - 2;
try {
stored = total(stored, 1, 2);
throw new AssertionError("overflow accepted");
} catch (ArithmeticException expected) {
check(stored == Long.MAX_VALUE - 2);
}
try {
total(Long.MIN_VALUE, -1);
throw new AssertionError("underflow accepted");
} catch (ArithmeticException expected) {
// Expected, including for a negative change.
}
System.out.println("total=25; overflow rejected; stored value unchanged");
}
}
Run and expected output
javac ExactTotal.java
java ExactTotaltotal=25; overflow rejected; stored value unchangedPrimary references
Continue with Java tutorials.