Learn Programming in Java


<<Previous | ToC | Next >>

Lesson #5: 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


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.
 

Next: Seaman

<<Previous | ToC | Next >>

Revised: 2021 May 19