Integer Overflow: What Happens at the Limits
You'll learn what happens when integer arithmetic pushes a value beyond its maximum or minimum boundary.
The Concept
Every integer type in Java has strict limits. For int, that's roughly -2.1 billion to +2.1 billion. But here's the surprise: Java doesn't stop you or throw an error when you exceed these limits. Instead, it silently wraps around to the opposite end, like an odometer rolling over from 999,999 back to 0.
Think of it like a circular number line. When you reach the maximum value and add 1, you don't keep going up—you loop back to the minimum value. Same thing in reverse: subtract 1 from the minimum, and you wrap to the maximum.
int maxInt = 2147483647; // Largest possible int value
int overflow = maxInt + 1;
System.out.println(overflow); // Prints: -2147483648 (the minimum!)
int minInt = -2147483648; // Smallest possible int value
int underflow = minInt - 1;
System.out.println(underflow); // Prints: 2147483647 (the maximum!)
This happens with all integer types—byte, short, int, and long. Each has its own range, but all wrap silently.
Why This Matters
This behavior is dangerous because Java gives no warning. Your program keeps running with incorrect values, potentially causing bugs that are hard to trace. If you're counting money, measuring distances, or doing any critical calculation, overflow can produce wildly wrong results without you knowing.
Key Takeaway: Integer overflow in Java wraps silently to the opposite extreme without errors—always be mindful of value ranges when performing arithmetic, especially with addition and multiplication.