BigInteger.intValue keeps only low-order bits when a value is out of int range, while intValueExact rejects the conversion.
Java BigInteger.intValueExact: reject a narrowing conversion
Validate the storage width
A wide external sequence number can parse correctly and still fail when stored in an int field. Silent narrowing can collide with an existing ID. The fixture uses 4294967297, whose low 32 bits equal one, to make the collision visible.
Call intValueExact when the target schema requires int, or keep the BigInteger through the workflow. Unsigned int parsing has a different representation contract: it interprets all 32 bits as an unsigned value, but still cannot hold an arbitrary BigInteger.
Reject before mutation
Convert and validate before inserting into a map or database. A failed exact conversion should not leave a partially updated record. Checked arithmetic addresses overflow during computation, not just narrowing.
Working program
import java.math.BigInteger;
public class ExternalSequenceWidthGate {
public static void main(String[] args) {
BigInteger externalId = new BigInteger("4294967297");
System.out.println("narrowed=" + externalId.intValue());
try { externalId.intValueExact(); }
catch (ArithmeticException rejected) { System.out.println("int range rejected"); }
}
}Output
narrowed=1
int range rejectedCost and ownership
The conversion itself is small, but parsing an arbitrarily long integer consumes memory and CPU proportional to its digits. Bound the input length. Losing high bits is a correctness fault, not a useful optimization.
Common Mistakes
- Do not use intValue for an externally assigned unique identifier without a range check.
- Do not assume a parsed BigInteger fits the next storage type.
- Do not confuse unsigned 32-bit interpretation with arbitrary precision.
Read next
Java checked integer arithmetic: reject overflow before updating state, unsigned integer parsing, long to double precision, Java Math.abs on Integer.MIN_VALUE: detect the one value that cannot turn positive.
