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.
Compute 13! with an int and with a long and print both.
Average two ints, a = 2_000_000_000 and b = 2_000_000_000, the wrong way and the safe way.
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
Explain two's complement and show how -1 is stored in a byte.
Why does long ms = 1000 * 60 * 60 * 24 * 365; give a wrong answer, and how do you fix it?
Why is Math.abs(Integer.MIN_VALUE) negative?
Why is (low + high) / 2 a bug in binary search, and what are two correct alternatives?
How would you guard a money calculation against overflow?
Expected output
micros per day, wrong: 500654080
micros per day, right: 86400000000
bad mid: -397483648
good mid: 1750000000
shift mid: 1750000000