Integer Arithmetic & Overflow
Understand integer division, modulus, overflow behavior, and how to detect it.
Integer Arithmetic & Overflow is a free Java Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Java Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Integer Arithmetic & Overflow
Java integers have fixed sizes. When a calculation exceeds the maximum or minimum value, it wraps around silently — no exception is thrown. Understanding this prevents subtle bugs.
Integer Ranges
Each integer type has a bounded range determined by its bit width:
byte: -128 to 127short: -32,768 to 32,767int: -2,147,483,648 to 2,147,483,647long: -9.2 × 10^18 to 9.2 × 10^18
System.out.println(Integer.MAX_VALUE); // 2147483647
System.out.println(Integer.MIN_VALUE); // -2147483648
System.out.println(Long.MAX_VALUE); // 9223372036854775807
System.out.println(Byte.MAX_VALUE); // 127Overflow: Silent Wrap-Around
Adding 1 to Integer.MAX_VALUE wraps to Integer.MIN_VALUE. This is two's complement arithmetic — Java makes no guarantee and throws no exception.
int max = Integer.MAX_VALUE;
System.out.println(max + 1); // -2147483648 (overflow!)
byte b = 127;
b++; // wraps to -128
System.out.println(b); // -128
// Real bug: counting votes in a large election with int
int votes = Integer.MAX_VALUE;
votes += 100; // silently wrong
System.out.println(votes); // negative number!Detecting Overflow with Math.addExact
Java 8+ introduced Math.addExact(), multiplyExact(), and subtractExact() which throw ArithmeticException on overflow instead of silently wrapping.
try {
int result = Math.addExact(Integer.MAX_VALUE, 1);
} catch (ArithmeticException e) {
System.out.println("Overflow detected!"); // prints this
}
try {
long safe = Math.multiplyExact(100_000L, 100_000L);
System.out.println(safe); // 10000000000
} catch (ArithmeticException e) {
System.out.println("Multiply overflow");
}Integer Division and Modulus
Integer division truncates toward zero. The % operator gives the remainder with the sign of the dividend. Watch out for division by zero — it throws ArithmeticException.
System.out.println(10 / 3); // 3 (not 3.33)
System.out.println(10 % 3); // 1
System.out.println(-10 % 3); // -1 (sign follows dividend)
System.out.println(-10 % -3); // -1
try {
int x = 5 / 0; // ArithmeticException: / by zero
} catch (ArithmeticException e) {
System.out.println(e.getMessage()); // / by zero
}
// Float division by zero gives Infinity, not exception
System.out.println(5.0 / 0); // InfinityLong Arithmetic for Large Numbers
Use long when values may exceed int range. Always append L to long literals to prevent overflow before the assignment.
// Bug: multiplication done as int, then widened
long wrong = 1_000_000 * 1_000_000; // overflows int!
System.out.println(wrong); // -727379968 (wrong!)
// Fix: one operand is long
long correct = 1_000_000L * 1_000_000L;
System.out.println(correct); // 1000000000000
// Or cast first
long alsOk = (long) 1_000_000 * 1_000_000;
System.out.println(alsOk); // 1000000000000Bit Shift Operators
Bit shift operators are fast ways to multiply/divide by powers of 2:
n << k— left shift: multiply by 2^kn >> k— signed right shift: divide by 2^kn >>> k— unsigned right shift: fills with 0s
int n = 8;
System.out.println(n << 1); // 16 (8 * 2)
System.out.println(n << 2); // 32 (8 * 4)
System.out.println(n >> 1); // 4 (8 / 2)
System.out.println(n >> 2); // 2 (8 / 4)
// Check if number is power of 2
boolean isPow2 = n > 0 && (n & (n - 1)) == 0;
System.out.println(isPow2); // trueBitwise AND, OR, XOR
Bitwise operators work on individual bits and are used in permissions, flags, and low-level protocols.
int a = 0b1010; // 10
int b = 0b1100; // 12
System.out.println(Integer.toBinaryString(a & b)); // 1000 (AND = 8)
System.out.println(Integer.toBinaryString(a | b)); // 1110 (OR = 14)
System.out.println(Integer.toBinaryString(a ^ b)); // 0110 (XOR = 6)
System.out.println(Integer.toBinaryString(~a)); // ...11110101 (NOT)
// Permission flags example
int READ = 0b001;
int WRITE = 0b010;
int EXEC = 0b100;
int perms = READ | WRITE; // user has read+write
System.out.println((perms & EXEC) != 0); // false — no execUnderscores in Numeric Literals
Java 7+ allows underscores in numeric literals to improve readability. They are ignored by the compiler.
int million = 1_000_000;
long creditCard = 4_111_1111_1111_1111L;
double pi = 3.141_592_653_589_793;
int hex = 0xFF_EC_D1_2E;
int binary = 0b0001_0101_0110;
System.out.println(million); // 1000000
System.out.println(creditCard); // 4111111111111111BigInteger for Arbitrary Precision
When values exceed long, use BigInteger. It has no overflow but is slower than primitives. Use it for cryptographic keys, factorials, and astronomical numbers.
import java.math.BigInteger;
BigInteger factorial100 = BigInteger.ONE;
for (int i = 2; i <= 100; i++) {
factorial100 = factorial100.multiply(BigInteger.valueOf(i));
}
System.out.println(factorial100.toString().length() + " digits"); // 158 digits
BigInteger a = new BigInteger("999999999999999999999999999999");
BigInteger b = new BigInteger("1");
System.out.println(a.add(b)); // 1000000000000000000000000000000Practical: Overflow-Safe Counter
A pattern for implementing a counter that handles overflow safely by using Math.addExact and falling back to Long.MAX_VALUE.
class SafeCounter {
private long count = 0;
public void increment() {
try {
count = Math.addExact(count, 1L);
} catch (ArithmeticException e) {
count = Long.MAX_VALUE; // cap at max
}
}
public long get() { return count; }
}
SafeCounter sc = new SafeCounter();
sc.increment();
sc.increment();
System.out.println(sc.get()); // 2Quick Check
What is the value of the following expression?
long result = 1_000_000 * 1_000_000; System.out.println(result);
Recap: Integer Arithmetic & Overflow
Key takeaways:
- Integer overflow wraps around silently — no exception by default
- Use Math.addExact/multiplyExact/subtractExact to catch overflow
- Integer division truncates toward zero; % sign follows dividend
- Use long literals (L suffix) when intermediate results may overflow int
- BigInteger handles arbitrarily large values without overflow
- Bit shift operators are fast alternatives to power-of-2 multiply/divide
Frequently asked questions
Is the “Integer Arithmetic & Overflow” lesson free?
Yes — the full text of “Integer Arithmetic & Overflow” is free to read here on the web, and the Java Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Java Academy course, upgrade to CoddyKit PRO.
What will I learn in “Integer Arithmetic & Overflow”?
Understand integer division, modulus, overflow behavior, and how to detect it. You practise Java Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Java Academy?
No prior experience is required. Java Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Integer Arithmetic & Overflow” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Java Academy lesson?
Yes. Every Java Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- The Math Class Essentials
- Integer Arithmetic & Overflow
- BigDecimal for Financial Calculations
- NumberFormat and printf