Student: My program is adding a list of positive ints in a loop, but the total ends up negative! What happened?
Teacher:
int
can only store numbers up toInteger.MAX_VALUE
, after which it wraps around to negative values.
Student: Huh? Why do we call it
int
then? That's not how integers work!
Teacher: Uh, well, it's an abstraction, but some abstractions aren't perfect.
Student: [looks up
Integer.MAX_VALUE
...] Why is the maximum value 2147483647? That's a pretty arbitrary number.
Teacher: Computers represent integers in binary... [mini-lecture follows]
Student: Okay, fine. But
Integer.MIN_VALUE
is -2147483648; why isn't it symmetric? What happens if we negateInteger.MIN_VALUE
, then?
Teacher: [two's complement mini-lecture]
You may or may not want to teach a specific lesson on binary (and octal and hex, and depending on your students, the concept of place value in general), but your students are going to run into leaky abstractions at some point, and you should be prepared to provide just-in-time education.
If you're working in a language with arbitrary-precision integers, you get to delay this line of questioning until your students wonder why addition suddenly gets slower once the values get large enough. General understanding of how values are physically represented will also help students with questions like "My program runs great on my desktop, but when I tried to run it on a Raspberry Pi, it runs out of memory. How can I make it use less memory?"