Search code examples
javafor-loopshort

Bug in for loop with short primitive in Java?


I've found a very odd thing in Java which seems to be a bug. A for loop doesn't to correctly evaluate the condition for a short value at 32767 (the maximum value, see here). See the example code below. Am I missing something here?

for (short i = 32766; i <= 32767; i++) {
    System.out.println("i is now " + i);
    if (i < 0) {
        System.out.println("This should never be printed");
        break;
    }
}

Expected output:

i is now 32766
i is now 32767

Actual output:

i is now 32766
i is now 32767
i is now -32768
This should never be printed

Solution

  • Every possible short value is <= 32767, because 32767 is the biggest number that a short can hold.

    That means that the condition of your if will always be true and your loop will never end.

    The value wraps around to Short.MIN_VALUE due to overflow (which does not throw an exception in Java).

    General note: there are very few legitimate reasons to use a short in Java, almost all calculation, loop counting and so on should be done with int (or long as appropriate). short isn't generally any faster and it won't generally save you any space (except if you have an array).