Numeric overflow
That's how Java and similar languages handle numeric overflow. In order to illustrate it, you can write a much simpler code:
public static void main(String[] args)
{
int intV = Integer.MAX_VALUE;
System.out.println(intV + 1);
}
which would produce -2147483648 as a result.
An answer on StackOverflow explains what happens under the hood, “binary-speaking”.
Note that doing this:
public static void main(String[] args)
{
int intV = Integer.MAX_VALUE;
long result = intV + 1;
System.out.println(result);
}
since the intV + 1 part will be evaluated first, and only after that, the resulting value will be cast to a long. However, this would give a positive result, because the addition is now performed on a long value:
public static void main(String[] args)
{
int intV = Integer.MAX_VALUE;
long result = (long)intV + 1;
System.out.println(result);
}
Specific handling of short
If you play with the first piece of code from my answer, you may end up writing code like this:
public static void main(String[] args)
{
short shortV = Short.MAX_VALUE;
System.out.println(shortV + 1);
}
You may be surprised to see that the result is 32768, which looks like nonsense since short can only store values from -32 768 to 32 767.
This is a particularity of Java (and similar languages such as C#) in a way the + operator works with short values. You can have a hint about what's going on by writing this piece of code:
public static void main(String[] args)
{
short a = 5;
short b = 4;
short c = a + b;
System.out.println(c);
}
This piece of code won't compile:
error: incompatible types: possible lossy conversion from int to short
What happens is that + operator first converts the short values to integers, and then produces the result. This is why in the piece of code above, you don't encounter a numeric overflow, since the addition is performed on an actual integer, and it's the value of an integer which is passed to println. On the other hand, this code:
public static void main(String[] args)
{
short shortV = Short.MAX_VALUE;
short result = (short)(shortV + 1);
System.out.println(result);
}
will display -32768, because even if the addition itself resulted in 32768, the cast of 32768 to short produced a numeric overflow.