# Head First Java - Chapter 4 puzzle question

William Wyatt
Greenhorn
Posts: 3
I'm trying to understand the pool puzzle problem on page 91 and hoping that someone can give me a hand. I can't figure out how the integer (ivar) gets any value assigned to it other than 0 and I can't understand how it works with 0 as the value. Below is a copy of the code.

public class Puzzle4 {
public static void main(String[] args) {
Puzzle4b[] obs = new Puzzle4b[6];
int y = 1;
int x = 0;
int result = 0;
while (x < 6) {
obs[x] = new Puzzle4b();
obs[x].ivar = y;
y = y * 10;
x = x + 1;
}
x = 6;
while ( x > 0 ) {
x = x - 1;
result = result + obs[x].doStuff(x);
}
System.out.println("result " + result);
}
}
class Puzzle4b {
int ivar;
public int doStuff(int factor) {
if (ivar > 100) {
return ivar * factor;
}else{
return ivar * ( 5 - factor );
}
}
}

p.s. This is my third head first book and I love them all.

Ernest Friedman-Hill
author and iconoclast
Marshal
Posts: 24211
35
Hi,

Welcome to JavaRanch!

Just looking at the Puzzle4b class by itself, you don't see the variable being assigned to anywhere. But look at Puzzle4, and you see

obs[x] = new Puzzle4b();
obs[x].ivar = y;

these two lines create a Puzzle4b instance, and set the value of ivar in that instance. Later, when obs[x].doStuff(x) is called, the Puzzle4b instance in obs[x] still has that nonzero value of ivar.

William Wyatt
Greenhorn
Posts: 3
Thank you very much, especially for the quick response. It seems so obvious now, don't know why I didn't see it before. Thanks again.

William Wyatt
Greenhorn
Posts: 3
One more quick question, in this section:

while ( x > 0 ) {
x = x - 1;
result = result + obs[x].doStuff(x);
}
System.out.println("result " + result);
}
}

Will the while loop run when x is equal to 0?

Ernest Friedman-Hill
author and iconoclast
Marshal
Posts: 24211
35
Nope.