Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!

# Array quiz I can't solve

Eddie Davis
Greenhorn
Posts: 16
I know this must be really simple but I can't solve it and need help to move forward. The book "Head First Java" provides the answer but I'm having trouble seeing how it got there.

here's the code snippet

I need to determine which of the reference variables refer to which objects. Not all the references variables will be used and some objects will be referred to more than once. Problem in the book "Head first Java" page 66.
The answer on page 69 shows
hq[0] pointing to nothing
hq[1] references id =1
hq[2] pointing to nothing
hq[3] references id=2
hq[4] references id=0

Nitish Bangera
Ranch Hand
Posts: 537
in the while loop

Rob Spoor
Sheriff
Posts: 20533
54
In these cases, you should just walk through the program, and keep track of what each array element is after each statement. In short, something like this:

Initially, x == 0 and hq = {null, null, null, null, null}
x == 0, loop body is executed; hq[x] is initialized: hq == {0, null, null, null, null}; x is increased to 1
x == 1, loop body is executed; hq[x] is initialized: hq == {0, 1, null, null, null}; x is increased to 2
etc

Eddie Davis
Greenhorn
Posts: 16
Thank you so much for explaining this! I think I understand now. I first needed to realize that my array was filled with nulls and that each pass through would increment a value. I have one more dumb question. Wouldn't the while loop begin with 1 instead of 0 because at the bottom of the while loop we add 1 to x with x = x + 1; And wouldn't that mean the array would begin with a null and then proceed with 1 and then 2?

Sorry but I just need to get this right in my head.

Rob Spoor
Sheriff
Posts: 20533
54
When the program comes to the while statement, x hasn't been increased yet. Therefore, it is still 0.

A while loop is really just that simple: you start at its beginning, and check if the condition (x < 3) is true. If so, you execute the body. You then start all over; if x < 3, you execute the body again. You keep doing this until x >= 3 (or more formally, until x < 3 will yield false). So in this case, the application will perform the following:

Eddie Davis
Greenhorn
Posts: 16
Ahh thank you. I understand now. Much appreciation to both of you helping me out with this.