I'm completely new to java and I decided to take a look at the book 'Head first java' which I know a lot of you guys have as well.

Well this is from the first mixed messages section, and here is the code:

The answer of the output is '00 11 21 32 42'

To me this the code is saying
1) X = 0
2) Y = 0
3) While X is less than 5 (which it is always)
4) y (0) = x (0) - y(0) and to me the sum of this is always 0 :S
5)Print out x(0) + blank space + y(0) + blank space

so to me the output should look like this
0 0 0 0 0 0 0 0 0 0 0 0 etc LOL =[

Could someone please explain it to me, because i'm feeling a bit demotivated by not even being able to do the first couple of exercises haha.

I think your analysis is correct...but you don't quite go far enough.

What do you suppose line 9 does?

I'm running it right now, exactly as you posted it, and am getting a LOT of output. I'm guessing you copied something wrong from the book, as this seems like a strange example.

It may look like it loops forever, but I'm rather sure it does stop eventually...

edit - found my copy of the book. I believe your line 9 should be

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors

Laurent Jones
Greenhorn

Joined: Jun 27, 2011
Posts: 6

posted

0

Oh I see! I must have missed the last line! Yes sorry, i did copy it wrong!

It was 'x = x +1' so that eventually the loop will end!

so first of all x and y are 0, so it will print out 00

Then int x = 0 + 1 = 1
y (0) = 0 + x(1) = 1

Then int x = 1+1 = 2
then int y(0) + x = 1

Then int x = 2+3 = 3
Then int y = (0)+x(2) = 2

Right I think i get that now...

Thanks for that guys, will definately be posting again haha.

FWIW, even with the " - 1", it would have ended...EVENTUALLY.

Integer-type variables have max. and min. values. If you reach the limit and then add/subtract one more (as appropriate), they 'roll over'. So you can see an extremely large positive value suddenly become a very small negative number, and vice versa.

So, you would get to a value of -2,147,483,648, subtract one more and get to a value of 2,147,483,647, which would then end the loop.

Laurent Jones
Greenhorn

Joined: Jun 27, 2011
Posts: 6

posted

0

Thanks very much for the information! I appreciate your help I'm doing a few more now, so If I don't get it, i'll post here.