arithmetic: companion code for the Add Two Numbers Without Overflow post
Silent int/long overflow reproduced with real numbers, the Math *Exact() family (addExact/subtractExact/multiplyExact/incrementExact/decrementExact/ negateExact/toIntExact/absExact) with the abs(MIN_VALUE) trap absExact exists to catch, widening to long vs BigInteger, and the XOR-based overflow bit trick Math.addExact uses internally, cross-checked against BigInteger ground truth over 100k random int pairs per JUnit repeat. Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01FhzLY5p6okFva3qsnsRyvM
This commit is contained in:
@@ -0,0 +1,16 @@
|
||||
$ java OverflowWrapDemo
|
||||
|
||||
=== int addition wraps silently past Integer.MAX_VALUE ===
|
||||
Integer.MAX_VALUE = 2147483647
|
||||
Integer.MAX_VALUE + 1 = -2147483648 (wrapped to Integer.MIN_VALUE, no exception)
|
||||
Integer.MIN_VALUE = -2147483648
|
||||
|
||||
=== A realistic case: summing item prices in cents overflows int ===
|
||||
priceCents * quantity = 1800000000 * 2 = -694967296 (should be 3,600,000,000 - this is wrong, and no exception was thrown)
|
||||
|
||||
=== Multiplication overflows just as silently as addition ===
|
||||
100000 * 100000 = 1410065408 (true value is 10,000,000,000)
|
||||
|
||||
=== long has the same problem, just a much higher ceiling ===
|
||||
Long.MAX_VALUE = 9223372036854775807
|
||||
Long.MAX_VALUE + 1 = -9223372036854775808 (wrapped to Long.MIN_VALUE)
|
||||
Reference in New Issue
Block a user