views:

1083

answers:

9
+24  Q: 

Endless for loop

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?

+14  A: 

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

org.life.java
126,127,-128,-127,... You missed one.
Jorn
@jorn yup :)...
org.life.java
+61  A: 

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...

Vladimir
does this answer really deserve 26 vote ups?
piemesons
@piemesons - YES!
mark
@mark i dont think so.
piemesons
@piermesons, frankly I agree with you - 29 votes may be too much for this answer, but that's just how SO works...
Vladimir
@piemesons: There are worse injustices in the world; such voting is a known issue and inevitable with this type of crowd-sourcing. Plenty of discussion about it on [meta](http://meta.stackoverflow.com). (FWIW, it is a good answer. ;)
Roger Pate
so what? 29 people didn't know this, and they become enlightened by this answer. good for them.
irreputable
I didn't know this (I even thought a byte went from 0 to 256!!), so I do think the answer deserves 37 upvotes.
Coronatus
@Coronatus, even an unsigned integer byte only ranges 0–255. Maybe you're thinking of the knob that goes to 11?
eyelidlessness
I'd say although this is a basic concept, it's easily missed, especially by less experienced programmers, and this answer is a nice and concise explanation.
nieldw
+10  A: 

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 ) {
paxdiablo
the only reason I can think of is for consistency, all the other integral types are signed, so if `byte` were to be unsigned, then it will be the odd one out.
Lie Ryan
Although the Common Type System in .NET has a similar limitation to signed types, if I recall correctly.
Joey
is it me or is your second snippet equal to what the op posted?
fortran
@fortran, it's just you :-) That's an `int`, which won't wrap around at 128 like the `byte` would.
paxdiablo
@paxdiablo He, he, true, I didn't notice the type change while visually scanning the loop structure :-)
fortran
+6  A: 

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

Itay
+5  A: 

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

Curd
+1  A: 

Best is if you do

for (byte i = 0 ; i < Byte.MAX_VALUE; i++ ) {
  System.out.println( i + 1 + " " + name );
}
krico
Best if you want to count from 0 to 126, that is :-)
paxdiablo
+39  A: 

Although the question is answered, some analogy for short (java) via xkcd

alt text

zengr
should be community wiki
SilentGhost
@SilentGhost: Should be a comment. @zengr: Is a link to xkcd really that onerous?
Roger Pate
I think this illustration is a good assist to the accepted answer.
Brad
http://i.imgur.com/pjp0e.png
Will
updated. @Will what is that link about?!
zengr
@zengr its about 32768
Will
@Brad: And it still would be as a comment on the question or that answer. Posting comics is fun, but not answers: so don't abuse the system.
Roger Pate
oh...common, explaining something in a humorous way does not mean its less "geeky". Peoples still get the point. A descriptive answer does not always have to be all code and text.
zengr
i fucking hate xkcd
zem
I understand posting a relevant XKCD comic to a discussion thread on Slashdot. But on *StackOverflow*? As an answer to an *already-answered* question, rather than as a comment to the accepted answer? And it gets *20+ upvotes*? Sheesh... I love XKCD, but apparently a lot of people REALLY love it.
Steve Perkins
@zem, your opinion is wrong.
eyelidlessness
A: 

this should work

        for (byte i = 0 ; i<128; ++i ) {
        if(i==-128)
            break;
        System.out.println( i + 1 + " " + "name" );
    }
Vivek Nandavanam
-1, because of two problems: 1: That will not work (overflow - goes to -128 without going through 128) 2: Even without the overflow, the `if (i==128)` condition block would never be executed - if it was, it would mean that the `for` loop could be entered even when its conditional for entry was false.
jhominal
@jhominal Yes it wont work, sorry about that. My initial answer was if(i==-128), later edited it to i==128. My bad. Have changed it back. Now it should work.:)
Vivek Nandavanam
Why not replace the `for` loop with `for (byte i = 0; i<128 ++i)`? That would get rid of the `break` statement.
jhominal
yes it would be simpler
Vivek Nandavanam
simpler, but tricky (bad): `for (byte i = 0; i != (byte) 128; ++i) {`
Carlos Heuberger
Also simpler: `for (byte i = 0; i >= 0; ++i) {`
Don Roby
I think this needs to be golfed.
eyelidlessness