Learn Programming in Java


<<Previous | ToC | Next >>

Arrays

An important use of iteration is to step through arrays of data, one item at a time. An array is any data type, repeated (different values) some specified number of times. Except for "final" arrays of constants, Java arrays are all dynamic, which is sort of like an object, only different. We will get into objects later, but objects and arrays are both created using the keyword "new":
int[] intary; // declared, but not yet exists
int[] myary = new int[99]; // declared and created but (probably) undefined
final int[] nums = {3,1,4,1,5,9,2,6,5,3,5};
    // constant array with 11 predefined elements
intary = new int[1000]; // now allocated memory for 1000 numbers
for (int n=0; n<1000; n++) intary[n] = 0; // now it has known values
for (int i=0; i<99; i++)
  myary[i] = nums[i%11]; // filled with 9 copies of nums


In many programming languages aggregate data (one name applied to a group of many values) like arrays, you mostly cannot do anything to the whole group at once, excxept maybe point to it (use its name). If you want to set all the values at once, you really need to write an iteration to do it, one element at a time (as in the two for-loops above). If you want to print all the values on a single line, you still need to do it with an iteration, one element at a time. For example, if you write in Java:

System.out.print("nums = " + nums);
it will print out some gibberish that the geeks will understand as referring to the whole group of numbers, and the rest of us will only see as gibberish. To get what you want, you need to do it one element at a time:
System.out.print("nums = ");
for (int n=0; n<nums.length(); n++)
  System.out.print(" " + nums[n]); // (or "" for no spaces)


In real life, we can draw pictures of array data as a single box with little boxes of elements inside (like the title screen in the Seaman video:

But in reality (which Java forces on you), it's just the little boxes that you must program individually. So here's the gotcha. Suppose you write something like this (using the declarations above)

intary = myary;
intary[3] = 88;
System.out.print("myary[3] = " + myary[3]);


In the first of these two lines, variable intary stops being 1000 numbers, and instead becomes another reference to the same array that myary points to. So when you change an element in intary (the second line), you also at the same time changed the corresponding element of myary. So what do you think the print line will print out? Try it. Did you expect 88 or 1? Computers can do strange stuff like this (and it's actually useful) that cannot happen in the real world. Notice that the original nums array was not changed, because we copied its elements one at a time, rather than taking a reference to the whole array. Any time you use the keyword "new" you get a reference to a whole clump of data. Assigning (copying) that reference to another variable of the same type (like the first of these last three lines) always points to the same clump of data. You can send this reference off to a subroutine to do things to the data, and it has a copy of your reference -- perhaps even a different name, but still the same actual data -- so that subroutine can make changes, and your original copy got changed, so you can use what it did in subsequent calculations. If you don't want it making changes, you can make another copy of the data, but it's extra work.

Underneath the covers a String is also an array, but (as we have already seen) it has special uses, and mostly we do not want to step through the characters one at a time. When we do, there is an accessor method to do that, but it only lets us look; for efficiency, you are not allowed to change the characters in a String, you can only make a new String as changed. But you can make arrays of String, and even arrays of arrays.

Like C (which Java mostly copied), all Java arrays start at element number ("index") zero, and the last element in any array has an index one less than the number (size) you used to create it. It is an error if you try to access the array with an index less than zero or greater than the highest actual element index. Java checks every array access: the array must exist, and the specified index must be within the bounds. This much you need to know, because if there's a problem, your program will get an exception ("crash",  see "Exceptions" in the "Things You Need to Know" page).

If you plan to write computer programs professionally, you might also want to read my (optional) comments on array bounds checking.

Later on you might decide to program a Tic-Tac-Toe game. You can define the game board as TTTboard[3][3], or you can linearize it to TTTboard[9] and separate the rows and columns in software, which is somewhat faster -- but not enough to notice. Programmers get to make these kinds of choices and trade-offs. But Tic-Tac-Toe is pretty challenging. Let's start with an easier game, Seaman. It's a game that uses iteration and arrays and other fun stuff to program it. You might have played something like Seaman when you were younger, drawing a stick figure of a guy on a (ahem) dangerous journey when the letters of a word are not guessed. We will write a program that plays scorekeeper for two humans playing Seaman.
 

Subroutines

The other important concept we already used in the English version of our next game Seaman is Subroutines or as they are called in Java, Methods. You might go back and review what we already saw in the Java Six when we get ready to use them in Seaman, coming up next.
 

Next: Seaman

<<Previous | ToC | Next >>

Revised: 2021 October 12