I have this code that runs but never stops.
class A {
public static void main(String[] args) {
for (byte index = 0; index < 128; index++)
{
System.out.println(index);
}
}
}
Can someone explain to me why it keeps looping.
In Java,
bytecan only represent values between -128 and 127. This means that every possible value ofindexis less than 128, and the loop cannot terminate with the current condition. Whenindexreaches 127, it simply overflows to -128 and the loop carries on.For more details on Java’s integral types, see the JLS.