Watch values wrap around
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
max = 2147483647
max + 1 = -2147483648
min - 1 = 2147483647
byte 127+1 = -128
abs(min) = -2147483648
-min = -2147483648
binary of -5 as int: 11111111111111111111111111111011