Java Add Two Counts Safely
Combining two counts looks trivial until the result exceeds its representation. State whether negative values and overflow are valid before choosing the operation.
Understand the idea
Use an integer type for whole counts, validate the domain and select checked arithmetic if silently wrapping would be wrong. The inputs below represent two independently validated groups. A reusable method should expose its accepted range and its overflow behaviour instead of returning an apparently plausible negative total.
Run it locally
Use a local JDK 21 or newer. Save the complete example as Main.java in a separate lab folder, then compile and run it with the commands below. Java examples do not run in Bhylu’s browser playground. The -ea option enables assertion checks used by some lessons.
javac --release 21 -encoding UTF-8 -d out Main.java
java -ea -cp out MainA worked example
public class Main {
static int addCounts(int first, int second) {
if (first < 0 || second < 0) throw new IllegalArgumentException("negative count");
return Math.addExact(first, second);
}
public static void main(String[] args) {
System.out.println(addCounts(7, 6));
}
}
Expected output
13Both counts pass the non-negative check, and addExact returns thirteen. Integer.MAX_VALUE plus one would throw rather than wrap. Test the zero identity, ordinary values and a boundary that cannot fit, since those cases exercise different parts of the contract.
Check the official Java documentation for detailed contracts and supported options.