Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected endless byte for loop

byte is a 1-byte type so can vary between -128...127, so condition i < 128 is always true. When you add 1 to 127 it overflows and becomes -128 and so on in a (infinite) loop...


After 127, when it increments, it will become -128, so your condition won't match .

byte: The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive). The byte data type can be useful for saving memory in large arrays, where the memory savings actually matters. They can also be used in place of int where their limits help to clarify your code; the fact that a variable's range is limited can serve as a form of documentation.


It will work like this:

0, 1, 2, ..., 126, 127, -128, -127, ...

as 8 bits can represent a signed number up to 127.

See here for the primitive data types.


Picture says more than words alt text


Because bytes are signed in Java so they will always be less than 128.

Why Java chose signed bytes is a mystery from the depths of time. I've never been able to understand why they corrupted a perfectly good unsigned data type :-)

Try this instead:

for (byte i = 0 ; i >= 0; ++i ) {

or, better yet:

for (int i = 0 ; i < 128; ++i ) {

because when i == 127 and and you executes i++ it overflows to -128.


The type byte has a range of -128..127. So i is always less than 128.