Bearish_Boring_dude
Bearish_Boring_dude

Reputation: 627

why is this loop working infinitely?

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 loop goes on infinitely . I would appreciate it if somebody could answer why ?

Upvotes: 3

Views: 131

Answers (3)

jlordo
jlordo

Reputation: 37843

This

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

is an infinite loop, because i will always be <= 255.

As Java bytes are signed, their value can range from -2^8(is -128) to (2^8)-1 (is 127).

Once i is 127, adding one will turn it to -128 which is obviously smaller than 255. So this loop will run forever.

Upvotes: 4

maerics
maerics

Reputation: 156662

Because byte values are in the range of [-128, 127].

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

Upvotes: 2

Jack
Jack

Reputation: 133669

Because any numerical value in Java is by default signed.

So a byte holds values in range [-128, 127], a range that always satisfies the condition of your for loop. Whenever i == 127, adding 1 to i turn it into -128.

Upvotes: 9

Related Questions