How to Store Values in an Array in Java - dummies

By Barry Burd

After you’ve created an array in Java, you can put values into the array’s components. For example, imagine you are the owner of a motel. The guests in Room 6 are fed up with all those mint candies that you put on peoples’ beds. They check out, and Room 6 becomes vacant. You should put the value 0 into the 6 component. You can do it with this assignment statement:

guestsIn[6] = 0;

On one weekday, business is awful. No one’s staying at the motel. But then you get a lucky break. A big bus pulls up to the motel. The side of the bus has a sign that says “Loners’ Convention.” Out of the bus come 25 people, each walking to the motel’s small office, none paying attention to the others who were on the bus. Each person wants a private room.

Only 10 of them can stay at the Java Motel, but that’s okay, because you can send the other 15 loners down the road to the old C-Side Resort and Motor Lodge.

Anyway, to register ten of the loners into the Java Motel, you put one guest in each of your ten rooms. Having created an array, you can take advantage of the array’s indexing and write a for loop, like this:

for (int roomNum = 0; roomNum < 10; roomNum++) {
 guestsIn[roomNum] = 1;

This loop takes the place of ten assignment statements because the computer executes the statement guestsIn[roomNum] = 1 ten times. The first time around, the value of roomNum is 0, so in effect, the computer executes

guestsIn[0] = 1;

In the next loop iteration, the value of roomNum is 1, so the computer executes the equivalent of the following statement:

guestsIn[1] = 1;

During the next iteration, the computer behaves as if it’s executing

guestsIn[2] = 1;

And so on. When roomNum gets to be 9, the computer executes the equivalent of the following statement:

guestsIn[9] = 1;

Notice that the loop’s counter goes from 0 to 9. Remember that the indices of an array go from 0 to one fewer than the number of components in the array. Looping with room numbers from 0 to 9 covers all the rooms in the Java Motel.

When you work with an array, and you step through the array’s components using a for loop, you normally start the loop’s counter variable at 0. To form the condition that tests for another iteration, you often write an expression like roomNum < arraySize, where arraySize is the number of components in the array.