This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
That is different code from page 63 in my copy of HFJ. My copy has int z = 0; The answer is not actually correct for the question asked. Both code snippets will compile correctly, but both will suffer an Exception, different in each case. The reason for the -1 is so entering the loop, the index used will be 0. You also have to change the < 4 to < 2 so you never have an index of 3 or greater.
If you cannot see why you need -1, get a pencil and paper. Starting at the line starting "while", write down the value of z, and which element in the array you are dealing with, as you go through the loop.
Joined: Oct 13, 2005
Tariq Ab wrote:. . . Couldn't we just set it to 0 and get it to loop 0 through 2? . . .
Yes, but that would make the exercise too easy. It is supposed to mimic the sort of question you get in certification exams.
The correct form of a for loop to initialise array elements is like this;Notice the only number literal you use is 0.