Question

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
Était-ce utile?

La 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).

Autres conseils

When you enter the for loop with Short.MAX_VALUE (which is 2^15 - 1, that is 32767) the condition i <= 32767 still holds!

As a result, i is incremented and you go into the loop once again... With i now being Short.MIN_VALUE.

Because the condition is <=32767 the condition is TRUE and the value of i is incremented once again. Since the max value of short is 32767, incrementing it by one makes i equal to -32768 which is still smaller or equal than 32767.

short: The short data type is a 16-bit signed two's complement integer. It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive). As with byte, the same guidelines apply: you can use a short to save memory in large arrays, in situations where the memory savings actually matters.

Take a look here: Primitive data types

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top