Hi,
I have the following loop.
for(byte i = 0 ; i < 128; i++){
System.out.println(i + 1 + " " + name);
}
When I execute my programm it prints all numbers from -128 to 127 in a loop. But the loop seems to be endless. Any ideas?
Hi,
I have the following loop.
for(byte i = 0 ; i < 128; i++){
System.out.println(i + 1 + " " + name);
}
When I execute my programm it prints all numbers from -128 to 127 in a loop. But the loop seems to be endless. Any ideas?
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 of127
(inclusive). Thebyte
data type can be useful for saving memory in large arrays, where the memory savings actually matters. They can also be used in place ofint
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
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...
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 ) {
The type byte has a range of -128..127. So i
is always less than 128.
Best is if you do
for (byte i = 0 ; i < Byte.MAX_VALUE; i++ ) {
System.out.println( i + 1 + " " + name );
}
Although the question is answered, some analogy for short (java) via xkcd
this should work
for (byte i = 0 ; i<128; ++i ) {
if(i==-128)
break;
System.out.println( i + 1 + " " + "name" );
}