Course outline

Kotlin / Language foundations and explicit state / Lesson 7

Checked integer arithmetic on the JVM

Detect Kotlin/JVM integer overflow using exact arithmetic.

About 20 min read20 worked examples20 practice exercisesContent reviewed
On this page

Lesson goals

  • Use exact JVM arithmetic when rejection is required.
  • Test numeric boundaries.
  • Trace exact JVM arithmetic and conversion order at Int and Long boundaries.
  • Design tests that distinguish representability, domain limits and unchanged state after failure.

Choose an overflow policy

Kotlin integer types have finite ranges, so a mathematical result may not fit even when both inputs are valid. On the JVM, ordinary Int arithmetic does not automatically report overflow. Choose a policy from the domain: reject an invalid result, use a wider type where sufficient, or deliberately accept wrapping. Document that policy and test its boundary rather than only small values.

Add with an exact check

On the JVM, java.lang.Math.addExact returns a sum that fits and throws ArithmeticException on overflow. The first example adds fixed values. Handle the exception at a boundary that can report or recover from it, rather than silently returning a plausible default. Check each intermediate calculation that may overflow; assigning a previously overflowed Int result to Long cannot restore the lost value.

kotlin Checked JVM addition
fun main() {
    println(Math.addExact(20, 22))
}
Expected output
42

The sum is representable as an Int.

Handle overflow

The second example deliberately adds one to Int.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. Kotlin targets other than the JVM need an appropriate target-specific arithmetic strategy instead of assuming a Java API is available.

kotlin Checked JVM addition
fun main() {
    try {
        Math.addExact(Int.MAX_VALUE, 1)
    } catch (error: ArithmeticException) {
        println("overflow")
    }
}
Expected output
overflow

The mathematical sum exceeds the Int range.

Review conversions

A wider destination does not change the type in which an earlier expression was evaluated. Convert operands before arithmetic when the wider operation is intended, and still verify the resulting range. Converting a value to a narrower type can lose information. Keep units explicit when numbers represent bytes, counts, or elapsed time, and validate external text before calculation.

Test numeric boundaries

Test zero, an ordinary sum, the largest valid result, and overflow. Assert the value or expected exception separately. If a calculation controls an allocation, enforce a practical size limit as well as representable arithmetic. Repeat the original failing input and confirm that callers receive the documented failure rather than a wrapped result. Keep fixed examples independent of machine time.

Choose a numeric contract first

An Int has a finite signed range from -2147483648 through 2147483647. Two inputs can each fit while their mathematical sum or product does not. In Kotlin/JVM ordinary Int arithmetic can wrap rather than throw on overflow, producing another representable bit-pattern that is not the mathematical answer. Decide whether the domain requires rejection, a sufficiently wide representation, arbitrary precision, or deliberately modular behavior before choosing an operator. A wrapped result must not be presented as a checked total merely because it is still an Int.

Record units and domain bounds as well as the machine type. A byte count cannot be safely added to a duration simply because both are integers, and an allocation that fits in Int may still be far too large for an application. Reject negative counts if the domain forbids them, set a practical maximum, and check each intermediate arithmetic step. A mathematical result within the final limit does not guarantee that an earlier multiplication or conversion was safe. This lesson uses Java standard-library facilities on the JVM and does not imply their availability on other Kotlin targets.

Check the operation and its inputs

java.lang.Math offers overloaded exact operations such as addExact, subtractExact and multiplyExact for int and long. A representable result is returned; an out-of-range result throws ArithmeticException. The overload depends on the operand types: supplying Int operands selects Int arithmetic, while Long operands select the Long overload. For Int.MAX_VALUE plus zero the result is the maximum; adding one with addExact throws. At the lower end, subtracting one from Int.MIN_VALUE also throws. Catch the exception only at a boundary that can return a truthful error or recover according to the application contract.

The exact operation checks representation, not domain validity. A negative number may fit Int while still being an invalid item count. Parse external input, validate its business constraints, and use the exact operation for the calculation. Do not wrap several unrelated operations in a broad catch and label every arithmetic failure as one specific invalid field. For a subtotal plus a fee, check the product and the addition separately so an overflow in either intermediate cannot silently corrupt the total. A failure should leave any protected state unchanged or follow a documented recovery policy.

Widen before computing and narrow after checking

Expression types matter before the assignment target. With a = Int.MAX_VALUE and b = 1, (a + b).toLong() first performs Int addition on the JVM and then widens the already wrapped Int result. In contrast, a.toLong() + b.toLong() computes 2147483648 as a Long, which can represent it. Widening is useful only when the wider range is sufficient for the entire computation; Long arithmetic can overflow too. Use the appropriate exact Long operation when the contract requires detection there.

Narrowing has the opposite risk. A Long may fit its own type but not the Int range. Check the target bounds before converting, or use Math.toIntExact on the JVM and handle ArithmeticException when the value is outside the Int range. A plain toInt conversion is not a range-validation policy. Validate both lower and upper limits, including negative values, and decide whether a rejected value should be reported to the caller. Converting a valid numeric value also does not validate its unit or its allowed business maximum.

Cover multiplication, division and signs

Multiplication can overflow even when neither input looks extreme. Math.multiplyExact checks the selected Int or Long operation; zero and negative operands are valid arithmetic inputs unless the domain forbids them. If a domain requires a nonnegative quantity, validate that rule separately rather than using an overflow exception as a substitute. For a product followed by addition, a successful product does not guarantee the addition will fit. Record which stage failed without exposing sensitive data or returning a plausible partial result.

Division has its own boundaries. A zero integer divisor causes ArithmeticException on the JVM. The special signed case Int.MIN_VALUE divided by -1 has a mathematical quotient one above Int.MAX_VALUE; ordinary JVM integer division does not signal that overflow and yields the wrapped minimum value. If rejection is required, check that special pair as well as zero before dividing, or use an appropriate checked facility supported by the project’s Java baseline. Ordinary negative integer division truncates toward zero; a remainder or rounded business rule must be specified separately. Do not test undefined or platform-dependent behavior as a substitute for a stated target contract.

Build a boundary-oriented test matrix

Use pairs that isolate each edge: a small normal result, zero, the largest accepted sum and the next rejected sum, plus the corresponding lower boundary. For multiplication, cover zero, a product that just fits under the chosen limits, and one that does not. Test conversion with both Int limits represented as Long and values one beyond them. For division, include a zero divisor and the minimum-value divided by -1 in addition to an ordinary negative case. Assert returned values and expected exceptions separately; a test that merely catches any exception can pass for the wrong reason.

For a resource allocation calculation, test the arithmetic check and the application’s practical maximum independently. If the calculation fails, verify the protected state or allocation count remains unchanged. Run fixed synthetic cases in an isolated JVM project with the documented Kotlin compiler and Java target when execution evidence is required, and record which cases ran. The snippets below are reasoned illustrations and remain unexecuted. Compiler mode, library support and domain policy must be checked separately; structural lesson validation does not execute arithmetic or prove production suitability.

20 worked examples

1. Small exact sum

Problem: Predict the checked sum of seven and five.

  1. Both operands select the Int overload.
  2. The mathematical sum 12 fits the Int range.
kotlin Illustrative JVM fragment
println(Math.addExact(7, 5))

This fragment requires surrounding context and was not executed or qualified as a standalone program.

Expected result: 12

Why this result follows: addExact returns the sum because it is representable as an Int.

2. Upper accepted boundary

Problem: What happens when zero is added to the maximum Int?

  1. The mathematical sum remains Int.MAX_VALUE.
  2. That result is representable, so the exact operation returns it.
kotlin Illustrative JVM fragment
println(Math.addExact(Int.MAX_VALUE, 0))

This fragment requires surrounding context and was not executed or qualified as a standalone program.

Expected result: 2147483647

Why this result follows: The upper boundary itself is accepted.

3. Upper overflow

Problem: What happens when one is added to maximum Int with addExact?

  1. The mathematical sum is 2147483648.
  2. That value exceeds the Int maximum, so the exact operation throws.
kotlin Illustrative JVM fragment
Math.addExact(Int.MAX_VALUE, 1)

This fragment requires surrounding context and was not executed or qualified as a standalone program.

Expected result: ArithmeticException

Why this result follows: The checked operation rejects the out-of-range sum.

4. Lower accepted boundary

Problem: What happens when zero is subtracted from minimum Int?

  1. The mathematical result remains Int.MIN_VALUE.
  2. The value is representable, so subtractExact returns it.
kotlin Illustrative JVM fragment
println(Math.subtractExact(Int.MIN_VALUE, 0))

This fragment requires surrounding context and was not executed or qualified as a standalone program.

Expected result: -2147483648

Why this result follows: The lower boundary is also accepted when no overflow occurs.

5. Lower overflow

Problem: What happens when one is subtracted from minimum Int?

  1. The mathematical difference is -2147483649.
  2. It is below the Int minimum, so subtractExact throws.
kotlin Illustrative JVM fragment
Math.subtractExact(Int.MIN_VALUE, 1)

This fragment requires surrounding context and was not executed or qualified as a standalone program.

Expected result: ArithmeticException

Why this result follows: A checked subtraction covers the lower boundary as well as the upper one.

6. Ordinary checked product

Problem: Predict the checked product of 12 and 7.

  1. The inputs select the Int multiplication overload.
  2. The product 84 fits in Int.
kotlin Illustrative JVM fragment
println(Math.multiplyExact(12, 7))

This fragment requires surrounding context and was not executed or qualified as a standalone program.

Expected result: 84

Why this result follows: multiplyExact returns the product when representable.

7. Product near the limit

Problem: Does the square of 46340 fit in Int?

  1. The mathematical square is 2147395600.
  2. That value is below Int.MAX_VALUE, so the checked operation returns it.
kotlin Illustrative JVM fragment
println(Math.multiplyExact(46340, 46340))

This fragment requires surrounding context and was not executed or qualified as a standalone program.

Expected result: 2147395600

Why this result follows: The test covers a large accepted product rather than only small inputs.

8. Product beyond the limit

Problem: Why is the next square rejected?

  1. The mathematical square is 2147488281.
  2. It exceeds 2147483647, so Int multiplyExact throws.
kotlin Illustrative JVM fragment
Math.multiplyExact(46341, 46341)

This fragment requires surrounding context and was not executed or qualified as a standalone program.

Expected result: ArithmeticException

Why this result follows: A nearby boundary case detects a product that no longer fits.

9. Negative arithmetic operand

Problem: Does exact multiplication itself reject a negative operand?

  1. The mathematical product is -12 and fits Int.
  2. The exact arithmetic operation returns it; a domain may separately forbid it.
kotlin Illustrative JVM fragment
println(Math.multiplyExact(-4, 3))

This fragment requires surrounding context and was not executed or qualified as a standalone program.

Expected result: -12

Why this result follows: Overflow checking and a nonnegative business rule are separate checks.

10. Zero product

Problem: What is the checked product when one operand is zero?

  1. The mathematical product of the maximum Int and zero is zero.
  2. Zero fits the selected Int result type.
kotlin Illustrative JVM fragment
println(Math.multiplyExact(Int.MAX_VALUE, 0))

This fragment requires surrounding context and was not executed or qualified as a standalone program.

Expected result: 0

Why this result follows: Large operands do not imply overflow when the actual result is representable.

11. Widen after overflow

Problem: What Long value results when ordinary Int addition happens first on the JVM?

  1. The Int addition wraps 2147483647 + 1 to Int.MIN_VALUE.
  2. toLong then widens that already wrapped value.
kotlin Illustrative JVM fragment
val a = Int.MAX_VALUE
val b = 1
println((a + b).toLong())

This fragment requires surrounding context and was not executed or qualified as a standalone program.

Expected result: -2147483648

Why this result follows: Widening the result cannot reconstruct the mathematical sum.

12. Widen before addition

Problem: What result is computed after widening both operands?

  1. Both operands become Long before the addition is evaluated.
  2. The sum 2147483648 fits Long.
kotlin Illustrative JVM fragment
val a = Int.MAX_VALUE
val b = 1
println(a.toLong() + b.toLong())

This fragment requires surrounding context and was not executed or qualified as a standalone program.

Expected result: 2147483648

Why this result follows: The arithmetic type is wider at the point where the sum is computed.

13. Long can overflow too

Problem: Does selecting the Long overload guarantee every sum fits?

  1. The operands select Long arithmetic.
  2. Long.MAX_VALUE plus one exceeds that type’s maximum and throws.
kotlin Illustrative JVM fragment
Math.addExact(Long.MAX_VALUE, 1L)

This fragment requires surrounding context and was not executed or qualified as a standalone program.

Expected result: ArithmeticException

Why this result follows: Widening the type changes the boundary but does not eliminate it.

14. Checked narrowing accepted

Problem: Can the Int maximum represented as Long be narrowed exactly?

  1. The Long value equals the upper Int boundary.
  2. toIntExact returns the equivalent Int.
kotlin Illustrative JVM fragment
println(Math.toIntExact(2147483647L))

This fragment requires surrounding context and was not executed or qualified as a standalone program.

Expected result: 2147483647

Why this result follows: The target boundary is representable and therefore accepted.

15. Checked narrowing rejected

Problem: What happens when a Long one above Int maximum is narrowed exactly?

  1. The value is outside the Int target range.
  2. toIntExact throws instead of returning a truncated Int.
kotlin Illustrative JVM fragment
Math.toIntExact(2147483648L)

This fragment requires surrounding context and was not executed or qualified as a standalone program.

Expected result: ArithmeticException

Why this result follows: Checked conversion rejects this value before information is lost.

16. Lower narrowing boundary

Problem: Can the Int minimum be converted from Long exactly?

  1. The Long value equals the lower Int limit.
  2. It is representable, so toIntExact returns that Int.
kotlin Illustrative JVM fragment
println(Math.toIntExact(-2147483648L))

This fragment requires surrounding context and was not executed or qualified as a standalone program.

Expected result: -2147483648

Why this result follows: A conversion test must include the negative boundary too.

17. Below the narrowing range

Problem: What happens one below the minimum Int?

  1. The Long value is lower than Int.MIN_VALUE.
  2. The exact conversion rejects it with ArithmeticException.
kotlin Illustrative JVM fragment
Math.toIntExact(-2147483649L)

This fragment requires surrounding context and was not executed or qualified as a standalone program.

Expected result: ArithmeticException

Why this result follows: Both sides of the target range need protection.

18. Zero integer divisor

Problem: What happens to integer division by zero on the JVM?

  1. The divisor is zero in an Int division.
  2. The division throws ArithmeticException before printing a quotient.
kotlin Illustrative JVM fragment
val divisor = 0
println(9 / divisor)

This fragment requires surrounding context and was not executed or qualified as a standalone program.

Expected result: ArithmeticException; no quotient

Why this result follows: A caller must define a zero-divisor policy before evaluating the operation.

19. Division’s special overflow

Problem: What does ordinary JVM Int division return for minimum Int divided by -1?

  1. The mathematical quotient is 2147483648, outside Int range.
  2. JVM integer division yields the minimum Int value for this special overflow.
kotlin Illustrative JVM fragment
println(Int.MIN_VALUE / -1)

This fragment requires surrounding context and was not executed or qualified as a standalone program.

Expected result: -2147483648

Why this result follows: A zero-divisor check alone does not reject this overflow case.

20. Check both stages

Problem: Compute a checked product followed by a checked fee.

  1. The first checked step produces 60.
  2. The second checked step adds 4 and returns 64.
kotlin Illustrative JVM fragment
val product = Math.multiplyExact(20, 3)
val total = Math.addExact(product, 4)
println(total)

This fragment requires surrounding context and was not executed or qualified as a standalone program.

Expected result: 64

Why this result follows: Separate checks cover both intermediate multiplication and final addition.

Common errors and fixes

A total wraps unexpectedly

Why it happens
An ordinary Int operation overflowed.
How to fix it
Use a checked operation where required.
Prevent it next time
Test the numeric boundary.

A Long result is already wrong

Why it happens
An Int expression overflowed before conversion.
How to fix it
Convert operands before arithmetic.
Prevent it next time
Review intermediate expression types.

A conversion loses information

Why it happens
A value was narrowed without range validation.
How to fix it
Check the target range before 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 Int.

Both arguments are Int values, and their mathematical sum is 42. That value is within the Int range, so the Int overload of Math.addExact returns 42 without throwing. This is a reasoned result for the fixed example, not a newly observed execution.

Check your solution

  • The mathematical sum is 42.
  • No overflow exception is expected for these operands.

2. Why can converting an overflowed Int result to Long be too late?

Show hint

Locate the type of the operation before locating the type of the destination.

Show worked solution

The earlier arithmetic already lost the mathematical result. Convert operands before the operation and check its range.

If two Int operands overflow during ordinary JVM addition, the result has already wrapped before a later toLong conversion. Convert operands to Long before addition when that range suffices, and check Long overflow too where the wider contract can reach its limit.

Check your solution

  • The conversion occurs before the arithmetic in the repaired calculation.
  • The wider range is checked against the actual input contract.

3. A JVM service accepts item count and unit price as nonnegative Ints. Design a checked subtotal and explain two different rejection causes.

Show hint

Business validation and representability are separate.

Show worked solution

Reject either negative input as a domain violation, then compute Math.multiplyExact(count, price). Report multiplication overflow separately from negative input so the caller can distinguish invalid data from an unrepresentable total.

Check your solution

  • Negative inputs are rejected before multiplication.
  • An overflowing nonnegative product is not returned as a valid subtotal.

4. A checked Int total is built from subtotal plus fee. Subtotal is Int.MAX_VALUE and fee is 1. Determine the outcome and state what must not be committed.

Show hint

A valid subtotal can still overflow in the next step.

Show worked solution

Math.addExact rejects the sum with ArithmeticException. Do not commit or expose a wrapped total; leave protected state unchanged or follow the documented recovery contract after reporting the overflow.

Check your solution

  • The addition is rejected.
  • No wrapped total is committed as success.

5. A product is calculated as Int and then converted to Long. For 50000 times 50000, explain the ordering defect and provide a safe calculation.

Show hint

Widen before multiplication, not after it.

Show worked solution

The mathematical product 2500000000 exceeds Int, so an ordinary Int product wraps before toLong can widen it. Convert operands to Long first and use Math.multiplyExact on Long values if the chosen contract requires overflow detection.

Check your solution

  • The intended product is 2500000000.
  • Conversion happens before multiplication.

6. An Int calculation uses Math.addExact twice: first 2147483640 + 7, then adds 1. Identify which step fails and the last valid value.

Show hint

Evaluate each checked intermediate in order.

Show worked solution

The first addition returns Int.MAX_VALUE, 2147483647. The second addExact attempts 2147483648 and throws ArithmeticException, so the application must not report a successful final total.

Check your solution

  • The first step returns 2147483647.
  • The second step throws before a final result is committed.

7. A checked subtraction starts at Int.MIN_VALUE + 2. Subtract 2, then attempt to subtract 1 more. Predict both outcomes.

Show hint

Trace the lower boundary step by step.

Show worked solution

The first subtraction returns Int.MIN_VALUE, -2147483648. The next subtractExact attempts -2147483649 and throws; a valid lower-bound result does not make a further decrement safe.

Check your solution

  • The first result is -2147483648.
  • The second subtraction throws ArithmeticException.

8. An allocation needs count * bytesPerItem plus a header. Design a two-stage exact calculation and a separate practical size check.

Show hint

Representability is not the application’s capacity policy.

Show worked solution

Validate nonnegative inputs, compute the product with multiplyExact and add the header with addExact using the chosen type. Then compare the result with the application’s practical maximum before allocating; handle each failure without allocation.

Check your solution

  • Both arithmetic stages are checked.
  • A representable but excessive size is rejected before allocation.

9. A Long value must be stored as Int. Design a test matrix using both Int boundaries and one value beyond each.

Show hint

Test lower and upper limits separately.

Show worked solution

Test -2147483648L and 2147483647L as accepted conversions, and -2147483649L and 2147483648L as rejected by Math.toIntExact. Assert the exact returned values or ArithmeticException rather than accepting any exception.

Check your solution

  • Both boundary values convert exactly.
  • Both outside values trigger ArithmeticException.

10. A programmer writes value.toInt() for an untrusted Long and claims the conversion validates range. Diagnose and choose a JVM checked alternative.

Show hint

A narrowing conversion and a range check are different operations.

Show worked solution

Plain toInt can discard information for values outside Int range; it does not reject them as invalid. Check both bounds before conversion or use Math.toIntExact and handle ArithmeticException at a boundary with a defined error response.

Check your solution

  • Out-of-range input cannot silently become an accepted Int.
  • The error policy is explicit.

11. A positive count is multiplied by zero in checked arithmetic. Does a zero result prove the count satisfies a maximum business limit?

Show hint

Arithmetic representability does not imply domain validity.

Show worked solution

The exact product is zero, but the input count may still exceed the application’s permitted maximum. Validate the count separately before multiplication, even though multiplying by zero cannot overflow.

Check your solution

  • The product is zero.
  • An excessive count is independently rejected.

12. A division helper promises to reject zero and unrepresentable Int quotients. Identify both exceptional input pairs or conditions it must check.

Show hint

Consider the special minimum-value divided by negative one.

Show worked solution

Reject a zero divisor, and also reject dividend Int.MIN_VALUE with divisor -1 because its mathematical quotient does not fit Int. Other accepted inputs still need any separate domain rules specified by the caller.

Check your solution

  • A zero divisor is rejected.
  • Int.MIN_VALUE divided by -1 is rejected rather than returned as a wrapped value.

13. For -11 divided by 3, state the Int quotient and remainder and explain why a floor-based business rule needs another step.

Show hint

JVM integer division truncates toward zero.

Show worked solution

The quotient is -3 and the remainder is -2, since -11 = 3 * -3 + -2. A rule requiring mathematical floor would use -4 instead, so implement and test that policy explicitly rather than assuming ordinary division provides it.

Check your solution

  • The quotient and remainder are -3 and -2.
  • The floor result is identified as -4.

14. A calculation catches Exception around input parsing and checked multiplication, reporting every failure as "bad number". Design a narrower failure boundary.

Show hint

Differentiate invalid text from arithmetic overflow.

Show worked solution

Parse and validate the text at its input boundary, then catch ArithmeticException around the exact multiplication where the application can report overflow. Do not relabel unrelated failures from other work as malformed numeric input.

Check your solution

  • Malformed text and overflow have distinct outcomes.
  • Unrelated exceptions are not silently converted to bad input.

15. A test asserts that some exception occurs for overflow but passes because an unrelated null access fails first. Strengthen the test.

Show hint

Reach the intended operation with controlled inputs.

Show worked solution

Construct non-null fixed inputs, invoke the specific exact operation, and assert ArithmeticException at that call. Add a nearby representable control that returns its expected value so an implementation that always throws cannot pass.

Check your solution

  • The intended exact operation is reached.
  • The valid control succeeds and the overflow case throws ArithmeticException.

16. A Kotlin library targets JVM and another target. Its code directly calls java.lang.Math.addExact. What portability claim can a reviewer make?

Show hint

The Java API is tied to the JVM boundary.

Show worked solution

The direct call is suitable only where the project’s JVM and Java baseline provides it. A non-JVM target needs an appropriate target-specific strategy and separate tests; the common source cannot assume the Java class exists there.

Check your solution

  • The JVM dependency is documented.
  • No cross-platform support is claimed without an implementation and test.

17. A counter at Int.MAX_VALUE must reject an increment without changing stored state. Outline an implementation and two assertions.

Show hint

Compute and validate before assigning.

Show worked solution

Compute the proposed value with Math.addExact before assigning it to the stored counter. If it throws, return the documented overflow outcome and leave the old value untouched; also test an ordinary increment that succeeds.

Check your solution

  • The maximum counter remains unchanged after rejection.
  • A normal increment updates to the expected value.

18. A system sums three nonnegative Int counts whose exact Long total may exceed Int. Choose a representation and define when narrowing is permitted.

Show hint

The caller’s required range determines the return type.

Show worked solution

Convert each count to Long before summing. The maximum of three nonnegative Int values is 6442450941, which fits Long; return Long if callers support it. Narrow with toIntExact only when an out-of-Int result must be rejected, and revisit overflow checks if the input count or types later change.

Check your solution

  • No intermediate Int sum is used.
  • Narrowing rejects totals outside Int range.

19. A function uses a negative Int as an item count but its exact multiplication fits. Explain why returning the product can still violate the contract.

Show hint

Checked arithmetic does not enforce the meaning of an operand.

Show worked solution

The exact operation can correctly return a negative representable product, but the item-count contract forbids the input. Reject the negative count before computation and test zero and a valid positive count as controls.

Check your solution

  • The negative input is rejected for a domain reason.
  • Valid zero and positive controls follow the stated policy.

20. Design a regression test for a total that previously wrapped at Int.MAX_VALUE + 1. Include an accepted boundary, rejected boundary and unchanged-state assertion.

Show hint

Test the exact failure and its effect, not only the exception.

Show worked solution

Use MAX_VALUE + 0 as the accepted control and MAX_VALUE + 1 as the overflow case through the checked function. Assert the first result, the documented overflow response for the second, and that the stored total was not changed by the failed update.

Check your solution

  • The accepted boundary returns Int.MAX_VALUE.
  • The rejected update leaves stored state unchanged.

Key takeaways

  • Choose overflow behavior explicitly.
  • Check intermediate operations and conversions.
  • Exact arithmetic rejects overflow but does not validate business rules.
  • Widen operands before calculation and check before narrowing.
  • Zero division and the minimum-value divided by -1 need distinct policies.

Official references