Java / Basic / Lesson 7
Checked integer arithmetic
Detect Java integer overflow with exact arithmetic and range tests.
On this page
Lesson goals
- Use exact arithmetic for a rejecting policy.
- Test arithmetic and conversion boundaries.
- Choose checked operations for intermediate calculations and conversions.
- Test both range boundaries, failure policy, and state preservation.
Choose an overflow policy
Java integer types have finite ranges, so a mathematical result may not fit even if both inputs are valid. Ordinary integer addition does not automatically report overflow. Decide whether the domain should reject an out-of-range result, use a wider type, or deliberately accept wrapping. Document the policy and test its boundary instead of relying only on small examples.
Add with an exact check
Math.addExact returns the sum when it fits and throws ArithmeticException on overflow. The example adds fixed values and prints the result. Handle the exception at a boundary that can report or recover from the invalid calculation; do not treat it as a normal total. Other exact methods cover selected arithmetic operations, so check each intermediate calculation that can overflow.
public class Main {
public static void main(String[] args) {
System.out.println(Math.addExact(20, 22));
}
}
42
The sum is representable as an int.
Handle overflow
The second example deliberately adds one to Integer.MAX_VALUE and handles the exception. A test should check both the maximum accepted result and the first rejected result. Catch the specific failure only where the application has a meaningful response; a broad catch that silently returns zero would turn an invalid calculation into plausible but incorrect data.
public class Main {
public static void main(String[] args) {
try {
Math.addExact(Integer.MAX_VALUE, 1);
} catch (ArithmeticException ex) {
System.out.println("overflow");
}
}
}
overflow
The mathematical sum exceeds the int range.
Check conversion order
A wider destination cannot repair an overflow that already happened in an int expression. Ensure the intended operand type is used before the operation, and check whether the wider range is itself sufficient. Narrowing a long to int can discard information; use a checked conversion when the application requires rejection. Also keep units explicit when calculating sizes or money.
Test numeric boundaries
Create a table with zero, an ordinary sum, the largest valid result, and an overflow. Assert the result or the expected exception separately. If the calculation feeds an allocation, validate the requested size and a practical application limit before allocating. Run the original failing input after the change and verify that callers receive the documented failure rather than a wrapped value.
Choose a numeric and domain policy
An integer type has a finite range. Inputs may each fit while their mathematical sum, difference, or product does not. Java ordinary int and long arithmetic retains fixed-width results and does not automatically throw on overflow. Before writing a calculation, decide whether the contract rejects overflow, uses a wider representation, or deliberately relies on wrapping. A business limit is a separate rule: a result can fit in int and still exceed a permitted order quantity. State units and permitted signs alongside the numeric range.
A rejecting policy should report a meaningful failure rather than quietly returning a plausible zero. Handle ArithmeticException at a boundary that can preserve state and communicate the chosen error. Do not catch every exception as if it were an arithmetic overflow; parsing failure, invalid input, and unavailable storage are different causes. Test an ordinary case, zero, the largest accepted result, and the first value outside each relevant boundary. If rejection must leave an object unchanged, compute and validate the proposed result before assigning it.
Check each intermediate operation
Math.addExact, subtractExact, multiplyExact, incrementExact, decrementExact, and negateExact detect overflow for their documented int or long overloads. The selected overload matters: an int operation is checked against the int range, while a long operation is checked against the long range. Math.toIntExact rejects a long value outside the int range. Exact operations are not arbitrary-precision arithmetic: they still reject results outside the chosen primitive type. If the domain truly needs a larger exact range, consider BigInteger with explicit input and resource limits.
Check the whole expression tree. In a price calculation, checking only the final addition is insufficient if quantity times price has already overflowed. Use multiplyExact for that product and addExact for the later fee in the intended type, with both failures handled under the contract. Convert operands before the operation when a wider exact overload is required. Test failure at the first intermediate operation and at a later one, along with a successful control, so the test demonstrates which boundary is protected.
Promote before calculating and check narrowing
The type of an operation is determined from its operands before assignment to a destination. If two int values are multiplied, assigning the already-overflowed int result to long does not recover the mathematical product. Cast an operand or use a long literal before multiplication, then assess whether the product fits in long. Widening can prevent an int overflow in a particular case but is not an unlimited safety guarantee. Choose checked long arithmetic when its overflow must also be rejected.
Converting a long to int with a cast can discard high bits and yield an unintended value. Math.toIntExact instead rejects a long that does not fit. Check a successful boundary and the adjacent rejected value on both positive and negative sides. Do not confuse a Java numeric range with a practical allocation limit: a mathematically valid byte count might still exceed the serviceโs configured memory budget. Validate nonnegative dimensions, operation results, and the application cap before allocating.
Handle division and negation boundaries
Integer division by zero raises ArithmeticException, but a zero check is not the entire division contract. In Java, Integer.MIN_VALUE divided by -1 overflows the mathematical int range and yields Integer.MIN_VALUE under the ordinary division operator; it does not signal overflow. If the application requires exact int results, explicitly reject that pair before division. For other integer inputs, division truncates toward zero and the remainder is related to the dividend. Test zero divisor, the exceptional minimum pair, negative values, and a normal result.
The most negative signed value has no positive counterpart in the same primitive range. Ordinary unary negation or Math.abs on Integer.MIN_VALUE therefore yields the same negative value rather than a positive magnitude. Java 17 offers negateExact and absExact for rejecting that overflow. Check the documented overload and type, and do not assume a later positive-range check can reconstruct the lost magnitude. A business contract may instead widen before negation when the wider type can represent the result, but must still validate its own permitted range.
Verify result, failure, and state
A boundary table should name the input types, mathematical expectation, selected policy, and observable result or exception. For a checked sum, include MAX_VALUE-1 plus 1 as an accepted boundary and MAX_VALUE plus 1 as rejected. Also cover the lower boundary rather than assuming positive overflow exercises subtraction or negation. When a calculation updates a stored value, assert both the error and unchanged state after rejection; a thrown exception alone does not establish atomic state behavior.
For repeatable evidence, run a complete test in an isolated environment with a recorded Java target, compiler, runtime, inputs, and exit status. A model trace can still teach the derivation, but it must not be described as measured execution. The fragments below are illustrative and require surrounding code. Use synthetic values and avoid allocating huge buffers simply to test arithmetic: compare the computed size with an explicit practical limit first. A passing boundary table supports the selected inputs and implementation; it does not prove all application arithmetic or every resource limit.
20 worked examples
1. Checked arithmetic trace 1
Problem: Compute a checked ordinary sum.
- Both operands are int and the mathematical sum is 27.
- The result fits in the int range, so no exception occurs.
int x=Math.addExact(12,15);
This fragment requires surrounding context; it was not executed as a standalone program for this example.
Expected result: x=27
Why this result follows: Exact addition returns a representable result.
2. Checked arithmetic trace 2
Problem: Compute the largest accepted int sum in this fixture.
- The first operand is one below the maximum.
- Adding one reaches the maximum without exceeding it.
int x=Math.addExact(Integer.MAX_VALUE-1,1);
This fragment requires surrounding context; it was not executed as a standalone program for this example.
Expected result: x=2147483647
Why this result follows: A boundary value can be valid even when the next sum is not.
3. Checked arithmetic trace 3
Problem: Trace ordinary int overflow in this stated fragment?
- The mathematical sum is one above the int maximum.
- The fixed-width ordinary addition wraps to the minimum int value.
int x=Integer.MAX_VALUE; int y=x+1;
This fragment requires surrounding context; it was not executed as a standalone program for this example.
Expected result: y=-2147483648
Why this result follows: The ordinary operator does not report overflow.
4. Checked arithmetic trace 4
Problem: Trace checked addition beyond the maximum.
- The mathematical result cannot fit in int.
- addExact reports the overflow instead of returning a wrapped sum.
int x=Math.addExact(Integer.MAX_VALUE,1);
This fragment requires surrounding context; it was not executed as a standalone program for this example.
Expected result: ArithmeticException
Why this result follows: The checked operation enforces a rejecting policy.
5. Checked arithmetic trace 5
Problem: Check subtraction below the int minimum.
- Subtracting one goes below the representable minimum.
- subtractExact detects the out-of-range result.
int x=Math.subtractExact(Integer.MIN_VALUE,1);
This fragment requires surrounding context; it was not executed as a standalone program for this example.
Expected result: ArithmeticException
Why this result follows: The lower boundary needs its own test.
6. Checked arithmetic trace 6
Problem: Compute an accepted lower-bound subtraction.
- The starting operand is one above the minimum.
- Subtracting one reaches the minimum exactly.
int x=Math.subtractExact(Integer.MIN_VALUE+1,1);
This fragment requires surrounding context; it was not executed as a standalone program for this example.
Expected result: x=-2147483648
Why this result follows: The lowest representable value remains valid.
7. Checked arithmetic trace 7
Problem: Compute a checked product within range.
- The mathematical product is two million.
- That value fits in a signed int.
int x=Math.multiplyExact(1000,2000);
This fragment requires surrounding context; it was not executed as a standalone program for this example.
Expected result: x=2000000
Why this result follows: multiplyExact returns the representable product. That value fits in a signed int.
8. Checked arithmetic trace 8
Problem: Check an overflowing int product.
- The mathematical product is 2,500,000,000.
- That exceeds Integer.MAX_VALUE. The exact int overload rejects the product.
int x=Math.multiplyExact(50000,50000);
This fragment requires surrounding context; it was not executed as a standalone program for this example.
Expected result: ArithmeticException
Why this result follows: The exact int overload rejects the product.
9. Checked arithmetic trace 9
Problem: Compute the same product with checked long operands.
- The L suffix selects long operands.
- 2,500,000,000 fits within long. Choosing the wider checked overload prevents this int overflow.
long x=Math.multiplyExact(50000L,50000L);
This fragment requires surrounding context; it was not executed as a standalone program for this example.
Expected result: x=2500000000
Why this result follows: Choosing the wider checked overload prevents this int overflow.
10. Checked arithmetic trace 10
Problem: Explain why a long destination is too late.
- Both operands are int during multiplication.
- The int product wraps before widening to long.
long x=50000*50000;
This fragment requires surrounding context; it was not executed as a standalone program for this example.
Expected result: x=-1794967296
Why this result follows: Assignment cannot recover the mathematical product.
11. Checked arithmetic trace 11
Problem: Check overflow in the wider primitive type.
- The sum exceeds the signed long maximum.
- The long overload of addExact detects it.
long x=Math.addExact(Long.MAX_VALUE,1L);
This fragment requires surrounding context; it was not executed as a standalone program for this example.
Expected result: ArithmeticException
Why this result follows: Widening from int does not make long unbounded.
12. Checked arithmetic trace 12
Problem: Convert the largest int value from long.
- The long value equals Integer.MAX_VALUE.
- It is within the target range and converts exactly.
int x=Math.toIntExact(2147483647L);
This fragment requires surrounding context; it was not executed as a standalone program for this example.
Expected result: x=2147483647
Why this result follows: A checked narrowing can succeed at the boundary.
13. Checked arithmetic trace 13
Problem: Check narrowing just beyond the int maximum.
- The value is one greater than Integer.MAX_VALUE.
- toIntExact rejects a value outside the target range.
int x=Math.toIntExact(2147483648L);
This fragment requires surrounding context; it was not executed as a standalone program for this example.
Expected result: ArithmeticException
Why this result follows: A checked conversion does not silently discard high bits.
14. Checked arithmetic trace 14
Problem: Trace an ordinary narrowing cast.
- The long value has low 32 bits 0x80000000.
- Those bits represent Integer.MIN_VALUE as an int.
int x=(int)2147483648L;
This fragment requires surrounding context; it was not executed as a standalone program for this example.
Expected result: x=-2147483648
Why this result follows: A cast permits information loss rather than rejecting it.
15. Checked arithmetic trace 15
Problem: Check negation of the minimum int.
- Its mathematical positive counterpart is 2147483648.
- That value does not fit in int.
int x=Math.negateExact(Integer.MIN_VALUE);
This fragment requires surrounding context; it was not executed as a standalone program for this example.
Expected result: ArithmeticException
Why this result follows: negateExact reports this asymmetric-range overflow. That value does not fit in int.
16. Checked arithmetic trace 16
Problem: Trace ordinary absolute value at the int minimum.
- The positive magnitude is outside the int range.
- Ordinary Math.abs returns the same negative minimum for this input.
int x=Math.abs(Integer.MIN_VALUE);
This fragment requires surrounding context; it was not executed as a standalone program for this example.
Expected result: x=-2147483648
Why this result follows: A nonnegative magnitude is not representable in int here.
17. Checked arithmetic trace 17
Problem: Check the Java 17 exact absolute-value alternative.
- The desired positive magnitude is outside int range.
- absExact rejects this overflow.
int x=Math.absExact(Integer.MIN_VALUE);
This fragment requires surrounding context; it was not executed as a standalone program for this example.
Expected result: ArithmeticException
Why this result follows: The exact variant makes the failure observable.
18. Checked arithmetic trace 18
Problem: Trace the special integer division overflow.
- The mathematical quotient 2147483648 is outside int range.
- Java ordinary integer division returns the minimum int for this pair.
int x=Integer.MIN_VALUE / -1;
This fragment requires surrounding context; it was not executed as a standalone program for this example.
Expected result: x=-2147483648
Why this result follows: A zero-divisor check alone does not reject this overflow.
19. Checked arithmetic trace 19
Problem: Determine integer division by zero.
- The divisor is zero when the expression is evaluated.
- Integer division cannot return a quotient for zero.
int x=7/0;
This fragment requires surrounding context; it was not executed as a standalone program for this example.
Expected result: ArithmeticException
Why this result follows: The caller needs an explicit invalid-divisor policy.
20. Checked arithmetic trace 20
Problem: Compute a two-stage checked total.
- The product 2,000,000 fits in int.
- Adding the fee 5 also fits and produces 2,000,005.
int product=Math.multiplyExact(1000,2000); int total=Math.addExact(product,5);
This fragment requires surrounding context; it was not executed as a standalone program for this example.
Expected result: total=2000005
Why this result follows: Both intermediate operations are checked independently.
Common errors and fixes
A total wraps unexpectedly
- Why it happens
- An ordinary int operation overflowed.
- How to fix it
- Use an appropriate checked operation.
- Prevent it next time
- Test the numeric boundary.
A long result is already wrong
- Why it happens
- The int expression overflowed before assignment.
- How to fix it
- Use the intended operand type before arithmetic.
- Prevent it next time
- Review intermediate expression types.
A cast loses information
- Why it happens
- A long value was narrowed without a range check.
- How to fix it
- Use a checked conversion.
- Prevent it next time
- Test values outside the target range.
20 practice exercises
1. What does Math.addExact(20, 22) return?
Show hint
Compare the mathematical sum with the int range.
Show worked solution
It returns 42 because the sum fits in an int.
Math.addExact(20,22) returns 42 because the sum of the int operands fits in int. This differs from the maximum-plus-one case, which throws ArithmeticException.
Check your solution
- The result is 42.
- These inputs do not overflow.
2. Why can assigning an int sum to long still be wrong?
Show hint
Determine operand types before assignment.
Show worked solution
The int addition can overflow before its result is widened. Choose the operand types before the addition.
With two int operands, int addition happens first and can wrap; assignment then widens the already incorrect result to long. Widen an operand before addition or use a checked long overload, and assess the long range too.
Check your solution
- A late conversion does not recover the mathematical sum.
- Required widening happens before addition.
3. A counter at MAX_VALUE-2 adds 2, then attempts to add 1. Under a reject-on-overflow policy, derive both outcomes and final state.
Show hint
Check each update before assigning.
Show worked solution
The first checked addition reaches MAX_VALUE. The second throws ArithmeticException, and if assignment occurs only after success the counter stays at MAX_VALUE; test both the result and unchanged state.
Check your solution
- The first update reaches MAX_VALUE.
- The rejected second update leaves the counter unchanged.
4. A balance is Integer.MIN_VALUE+2. Subtract 2 and then attempt another subtraction of 1 with subtractExact. What should a stateful test assert?
Show hint
Check the lower boundary and state after rejection.
Show worked solution
The first subtraction reaches MIN_VALUE. The next checked subtraction throws; preserve the stored minimum by assigning only after success and assert the documented failure.
Check your solution
- The first subtraction reaches MIN_VALUE.
- The failed subtraction leaves the stored value unchanged.
5. A calculation computes quantity 50,000 times price 50,000, then adds fee 5. Design checked long operations and derive the total.
Show hint
Promote before the product and check both stages.
Show worked solution
Use Math.multiplyExact(50000L,50000L) to obtain 2,500,000,000L, then Math.addExact(product,5L) to obtain 2,500,000,005L. Handle overflow of either long operation under the documented policy.
Check your solution
- The product is 2500000000L.
- The checked total is 2500000005L.
6. A product fits in int but adding a fee overflows. Construct concrete operands and explain which checked stage fails.
Show hint
Use a product at the maximum and a positive fee.
Show worked solution
For quantity 1 and price Integer.MAX_VALUE, multiplyExact returns MAX_VALUE. Adding fee 1 with addExact throws; asserting both stages prevents an unrelated product failure from masking the intended test.
Check your solution
- The checked product succeeds at MAX_VALUE.
- The fee addition throws ArithmeticException.
7. A calculation uses int a and b but needs a long sum. Compare (long)(a+b) with (long)a+b for a=MAX_VALUE and b=1.
Show hint
The cast position determines the addition type.
Show worked solution
In (long)(a+b), int addition wraps to MIN_VALUE before conversion. In (long)a+b, long addition yields 2147483648L; use checked long addition if long overflow is also possible.
Check your solution
- The late cast produces -2147483648L.
- The early cast produces 2147483648L.
8. A long value is -2147483648L or -2147483649L. Predict toIntExact for both.
Show hint
Compare each value with the int minimum.
Show worked solution
The first equals Integer.MIN_VALUE and converts exactly. The second is one below the range and throws ArithmeticException; a narrowing cast would not provide this rejection.
Check your solution
- The minimum boundary converts to -2147483648.
- The value below it throws.
9. A byte count is rows times columns times 4. For rows=100 and columns=200, derive checked size and apply a 100,000-byte application cap.
Show hint
Check intermediate products in a sufficient type.
Show worked solution
Using checked long multiplication gives 100*200*4=80,000 bytes, which fits under the stated cap. Validate nonnegative dimensions first; reject a checked overflow or a result above the cap before allocating.
Check your solution
- The computed size is 80000 bytes.
- The application cap permits this case.
10. A computed allocation size is 120,000 bytes and fits in long, but the service cap is 100,000. What should happen?
Show hint
Numeric validity does not imply business acceptance.
Show worked solution
Reject the size under the documented resource policy before allocation, despite the successful arithmetic. A separate 80,000-byte control should pass the cap check when other constraints are satisfied.
Check your solution
- 120000 exceeds the cap and is rejected.
- 80000 passes the cap check.
11. An int divisor is zero or -1; the dividend is MIN_VALUE. Define an exact-division guard for these cases and a normal control.
Show hint
Check both exceptional input pairs before dividing.
Show worked solution
Reject divisor zero and reject the MIN_VALUE/-1 pair when exact int results are required. A normal control such as 8/2 returns 4; only divide after the guard succeeds.
Check your solution
- Zero and MIN_VALUE/-1 are rejected.
- The normal control returns 4.
12. A distance calculation negates Integer.MIN_VALUE. Compare checked int negation with widening first.
Show hint
The long type can represent 2147483648.
Show worked solution
Math.negateExact on the int throws. Negating (long)Integer.MIN_VALUE yields 2147483648L, which is representable in long; apply any business range limit afterward.
Check your solution
- The int exact negation throws.
- The widened negation yields 2147483648L.
13. A method uses Math.abs on a signed int as an array size. Design a test for MIN_VALUE and a safe rejection policy.
Show hint
The minimum has no positive int counterpart.
Show worked solution
Math.abs(MIN_VALUE) remains negative, so it cannot be assumed a valid nonnegative size. Reject that input with absExact or explicit validation, then check the application allocation cap before allocating.
Check your solution
- MIN_VALUE does not produce a positive int magnitude.
- The invalid size is rejected before allocation.
14. A long counter at Long.MAX_VALUE must increment exactly. Compare incrementExact with an ordinary increment.
Show hint
Even long has a finite range.
Show worked solution
Math.incrementExact(Long.MAX_VALUE) throws ArithmeticException, while ordinary long increment wraps to Long.MIN_VALUE. Choose the checked operation for the rejecting contract and preserve state when it fails.
Check your solution
- incrementExact throws at the maximum.
- Ordinary increment wraps to the minimum.
15. A pipeline parses "12x" and then adds a fee. Distinguish parse failure from arithmetic overflow and provide one successful control.
Show hint
The arithmetic should not run on an unparsed value.
Show worked solution
Integer.parseInt("12x") throws NumberFormatException before addition. Handle that format failure separately from ArithmeticException; for valid "12" and fee 3, checked addition returns 15.
Check your solution
- Malformed input fails before addition.
- The valid control returns 15.
16. A checked int sum is 1,200, but an order permits totals only through 1,000. What does each check conclude?
Show hint
Arithmetic and domain limits are independent.
Show worked solution
The value 1,200 is representable, so exact arithmetic succeeds. The business rule then rejects it for exceeding 1,000; test a total of 1,000 as an accepted boundary.
Check your solution
- The arithmetic check succeeds for 1200.
- The business limit rejects 1200 and permits 1000.
17. A function returns 0 for both overflow and a valid zero sum. Design a failure contract and tests that distinguish them.
Show hint
Do not encode two meanings in an unreserved result.
Show worked solution
Propagate or translate ArithmeticException to an explicit failure under the API contract, while returning 0 for a valid zero sum. Test 0+0 as success and MAX_VALUE+1 as failure; do not silently substitute zero.
Check your solution
- The valid zero sum is returned.
- Overflow is observably distinct from zero.
18. An exact product is computed in long but later narrowed with (int). Design tests at Integer.MAX_VALUE and one above it.
Show hint
Check the conversion separately from the product.
Show worked solution
Use Math.toIntExact on the long result when int output is required. MAX_VALUE converts; MAX_VALUE+1L throws. Verify the product stage and conversion stage independently so a valid long result is not mistaken for a valid int.
Check your solution
- MAX_VALUE converts exactly.
- MAX_VALUE+1L is rejected by the conversion.
19. A sum loop stores each checked partial total in a field. The third item overflows and the contract requires all-or-nothing update. How should it be changed?
Show hint
Checked arithmetic alone does not roll back prior assignments.
Show worked solution
Accumulate into a local variable using addExact for every item, then assign the field only after the entire input succeeds. Test an overflowing third item and assert the old field remains unchanged; a valid list should commit its full sum.
Check your solution
- Overflow leaves the original field unchanged.
- A valid list commits the complete result.
20. A service needs exact results larger than long may hold. Compare BigInteger with unchecked long and identify a resource boundary.
Show hint
A wider representation still needs input limits.
Show worked solution
Use BigInteger when arbitrary-precision integer semantics fit the contract; unchecked long can wrap. Validate input size and operation budgets because larger numbers consume memory and time, and test both a value beyond long and a rejected oversized input.
Check your solution
- The chosen representation preserves the beyond-long result.
- An explicit input or resource limit is tested.
Key takeaways
- Choose and test an overflow policy.
- Check intermediate types before conversion.
- An int operation can wrap before assignment to long.
- Exact operations detect overflow within the selected type; they are not unbounded.
- Type range differs from business and resource limits.