0

When I start my code

for (byte i = 0; i < 1000; i++) {
    System.out.print(i);
}

I get infinite loop. Why?

JohnWinter
  • 1,003
  • 5
  • 12
  • 25

2 Answers2

5

Simply because byte value starts to overflow after its max value i.e. 127.

The value of i will go up to 127 and then will overflow to -128 and then increment back to 127. This process will therefore never satisfy your for loop termination condition, and thus loop forever.

Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136
  • after 127 it will wrap to -128 and count all the way up to 127 again. All of the possible values are less than 1000 so it won't ever exit – xkickflip Jul 12 '15 at 22:55
0

The maximum value of a byte is less than 1000.

AJF
  • 11,767
  • 2
  • 37
  • 64
Chris K
  • 1,703
  • 1
  • 14
  • 26