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
14 lines
674 B
Plaintext
14 lines
674 B
Plaintext
$ java WideningAndBigIntegerDemo
|
|
|
|
=== Widening to long fixes the int-range overflow from OverflowWrapDemo ===
|
|
int: Integer.MAX_VALUE + 1 = -2147483648 (wrong)
|
|
long: (long) Integer.MAX_VALUE + 1 = 2147483648 (correct)
|
|
|
|
=== Widening only raises the ceiling - long still overflows eventually ===
|
|
Long.MAX_VALUE + 1 = -9223372036854775808 (wrapped to Long.MIN_VALUE - same bug, bigger numbers)
|
|
|
|
=== BigInteger never overflows - it grows to fit the true value ===
|
|
BigInteger.valueOf(Long.MAX_VALUE).add(ONE) = 9223372036854775808
|
|
BigInteger.valueOf(2).pow(100) = 1267650600228229401496703205376
|
|
(that value has no exact long or int representation at all)
|