I have one question about the short data type in Java. I know that the range for short is between -32768 to 32767.
So, if I tried to add two short values that exceed the range, the result ends up being the supposed total minus either the positive range or the negative range times 2, as the following:
short a = 30000;
a = (short) (a+a);
the result is -5536.
So the math is 32768 + 32768 = 65536, 6000 – 65536 = -5536.
I know what it does, but I don’t know why it does it this way.
Can anybody explain the logic or why Java is doing it this way?
What’s happening is that your number is wrapping around. More specifically, you’ve got a number 30,000, which in binary is:
When you add it to itself, and carry the 1’s, you get:
(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 theintresult of the expression is narrowed to ashort. 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 theint(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 along, though it would take 65+ bits.