Overflowing Short in java

What’s happening is that your number is wrapping around. More specifically, you’ve got a number 30,000, which in binary is:

0111 0101 0011 0000

When you add it to itself, and carry the 1’s, you get:

1110 1010 0110 0000

(Note: it’s very easy to multiply a number by 2 in binary — just shift all the bits one to the left.)

A short is a signed number using two’s complement, meaning that that leftmost 1 is really a minus sign; that number represents -5536.

If you multiplied that number by 2 again, you’d need more than 2 bytes to represent it. Since you don’t have more than 2 bytes in a short, the extra bits would just get dropped when the int result of the expression is narrowed to a short. Do that enough, and you’ll have a 0 as the leftmost digit; the number is positive again. And then eventually you’ll have a 1 again as the leftmost; the number is negative again. Eventually you’ll have shifted all 0s into the number; multiplying any integer by 2 enough times will always result in 0 (specifically, if it’s an N-bit number, multiplying it by 2 N times will always result in 0).

If you weren’t narrowing to a short, you’d still eventually run out of digits in the int (when you need 33 or more bits) — this would result in the extra digits being dropped, which is integer overflow. The same thing would happen if either argument were a long, though it would take 65+ bits.

Leave a Comment