Strange endless loop result

exercise No. 208

Q:

We consider:

for (byte b = 0; b <= Byte.MAX_VALUE; b++);

This snippet causes an endless loop. Give an explanation.

Tip

Consider the ++ operator's behavior when reaching variable b's upper limit.

A:

Every variable of type byte is bounded by Byte.MAX_VALUE. The boolean expression b <= Byte.MAX_VALUE is thus always true.

A closer look reveals b++ oscillating between its lower Byte.MIN_VALUE and upper Byte.MAX_VALUE bound:

Code Output Explanation
byte b = Byte.MAX_VALUE - 1;
System.out.println(b++);
System.out.println(b++);
System.out.println(b++);
...
System.out.println(b++);
 126
 127
-128
-127
 ...
 127
Byte.MAX_VALUE
Byte.MIN_VALUE


Byte.MAX_VALUE

Instead of breaching the loop's upper limit Byte.MAX_VALUE our variable b will transition from Byte.MAX_VALUE to Byte.MIN_VALUE. The loop will thus continue forever.

An even closer look on the operator ++ acting on b of value of 127 (or Byte.MAX_VALUE) shows an overflow style behaviour:

One byte 2-complement Value
  01111111
+ 00000001
----------
  10000000
 127
+  1
----
-127