Why does this cycle run indefinitely?

class kk{
    public static void main(String args[]){
        int n=0;
        for (byte i = 0; i<=255; i++) 
        { 
             n++;
        }
        System.out.println(n);
    }
}

      

The above for the loop goes on forever. I would appreciate it if someone could answer why?

+3


source to share


3 answers


As the byte values ​​are in the range [-128, 127]

.



Hence, when byte 127 increases, it overflows to -128 and your loop continues indefinitely.

+2


source


As any numeric value in Java is signed by default .



So, byte

contains values ​​in a range [-128, 127]

, a range that always satisfies your loop condition for

. Whenever i == 127

, adding 1

to i

turns it into -128

.

+9


source


it

for (byte i = 0; i<=255; i++)

      

- an endless loop, because i

there will always be <= 255

.

As Java is signed, byte

their value can range from -2^8

(-128) to (2^8)-1

(up to 127).

Once i

equals 127, adding one will turn it to -128, which is obviously less than 255

. Thus, this cycle will run forever.

+4


source







All Articles