Detect it or avoid it
try/catch is explained in Phase 7. Here it just lets the program keep going after the error.
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
addExact caught: integer overflow
toIntExact caught: integer overflow
long result: 2147483648
BigInteger: 92233720368547758070