Command Palette

Search for a command to run...

Back to the lesson: Topic 1.3 — Integer Ranges and Overflow
Core Java · Example 2 of 3

Two famous overflow bugs and their fixes

Java integers have a fixed number of bits, so when a result is too big it silently wraps around to the other end of the range: Integer.MAX_VALUE + 1 is Integer.MIN_VALUE. Knowing how two's complement works lets you predict, detect and prevent overflow bugs.

Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Compute 13! with an int and with a long and print both.

02

Average two ints, a = 2_000_000_000 and b = 2_000_000_000, the wrong way and the safe way.

03

Compute the number of seconds in 100 years (365 days each) as an int and as a long, and use Math.toIntExact to show that it doesn't fit in an int.

Explain it without notes

01

Explain two's complement and show how -1 is stored in a byte.

02

Why does long ms = 1000 * 60 * 60 * 24 * 365; give a wrong answer, and how do you fix it?

03

Why is Math.abs(Integer.MIN_VALUE) negative?

04

Why is (low + high) / 2 a bug in binary search, and what are two correct alternatives?

05

How would you guard a money calculation against overflow?

Two famous overflow bugs and their fixes
Sign in to run this example in your browser.

Expected output

micros per day, wrong: 500654080
micros per day, right: 86400000000
bad mid:   -397483648
good mid:  1750000000
shift mid: 1750000000