ARRAYS IN JAVA

length multidimensional Exercises

An array is a group of variables. Those variables can be either primitives or objects, as long as all of the members of the group are the same type of thing. Here is some code that sets up an array of integers:

int[] magicNumber = new int[5];

This follows a general syntax of:

type[] nameOfArray = new type[sizeOfArray];

That line of code establishes the array itself; however, it does not fill the contents of the array. We have a container ready to hold five integers, but we still don't know what those five integers are. Here is how you fill the array:

magicNumber[0]= 4;

magicNumber[1]= 12;

magicNumber[2]= 7;

magicNumber[3]= 5;

magicNumber[4]= 26;

This is following a general syntax of:

nameOfArray[indexNumber]= value;

Note that the index is zero-based. The first element of the array has an index of 0 and the last element of the array has an index of 4, not 5. The array still holds five things. Making a mistake with indices is a common error in programming.

Once you establish your array, you can continue to refer to the elements of the array by their index number. For example, you might have this:

System.out.println(magicNumber[1]+ magicNumber[3]);

Would that produce a 17 on the screen or 125? Test it out.

The magicNumber array is a group of integers, but you can also make a group of objects using any of the classes available in Java. For example, you might want to have an array of your favorite colors. Setting it up works just like the array of integers:

Color[] favoriteColor = new Color[4];

favoriteColor[0] = new Color(0,160,160);

favoriteColor[1] = new Color(160,80,240);

favoriteColor[2] = new Color(80,0,190);

favoriteColor[3] = new Color(200,110,0);

You are seeing two different uses of the new keyword here. The first line uses "new" to create an array, while the following lines use "new" to call the class constructor from class Color. Those are the only uses of "new" in Java. The square brackets [ ] are only used for arrays.

So now I have a group of colors, and each element of the array can be used in any place I would use a variable of type Color. For example, I might want to set the background color of an applet or draw some graphics using one of my favorite colors stored in the array. The element of the array simply becomes an argument in a method call:

setBackground(favoriteColor[0]);

Notice that I named the array "favoriteColor." You might think that if it is a group of colors, I would want to use the plural form and name it "favoriteColors." That makes sense when you are thinking of the group as a whole, but it also means that you would need to refer to individual elements with the plural form, like this:

setBackground(favoriteColors[0]);

which you are certainly welcome to do. The problem is that you tend to forget. You make the array plural at the declaration and then you type it in as singular later on in the code. This produces an error that can be difficult to see. So, as a rule, I always use the singular form to name an array.

Java has also provided a shortcut method for establishing arrays. You can declare the array and fill it at the same time if you wish. For example, the magicNumber array could have been created with this code:

int[] magicNumber = {4,12,7,5,26};

It's a little confusing because it uses curly braces instead of square brackets. But it does work. The compiler automatically figures out that your array contains five elements.

Arrays work very well in combination with loops. For example, if you wanted to see all five of your magic numbers printed on the screen, you could do this:

for (int i = 0; i < 5; i++){

System.out.println(magicNumber[i]);

}

Notice how the zero-based indexing of the array works well with the format of the loop. You start at i=0 because 0 is the value of the first index in the array. Then you go up to i < 5, so that the highest value will be 4--exactly what you want for your index. Yet when you look at the loop code, you still see a 5 written there, which coincides nicely with the fact that there are five things in this array.

Of course, the size of the array might change. You might decide to have eight different magic numbers instead of five. Then you would have to go back and change all of your loops to say i < 8 instead of i < 5. This could be annoying if you had made reference to five in many places in the code. There is a way to avoid that annoyance. When you make your loop in the first place, you can refer to a special property of arrays known as "length":

for (int i = 0; i < magicNumber.length; i++){

System.out.println(magicNumber[i]);

}

You just use the syntax of:

arrayName.length

Notice that it does not have parentheses after it, even though you might be tempted to put them there.

I said at the beginning that you could have an array of anything. This also means that you can have an array of arrays! Suppose I have three different integer arrays:

int[] magicNumber = {4,12,7,5,26};

int[] uglyNumber = {29,87,3,52};

int[] secretNumber = {11,75,59};

I can group these together to create an array of integer arrays:

int[][] number = {magicNumber, uglyNumber, secretNumber};

If my code refers to this:

number[0]

I am talking about the entire array named magicNumber. I might end up saying something like:

int counter = number[0].length

because length is a property of arrays and number[0] is itself an array.

Contrast that to this reference:

number[0][4]

where I am talking about a specific element of the magicNumber array, namely the last one.

If I did this, I would get an error:

number[2][4]

Why?

An array of arrays is sometimes called a two-dimensional array. This makes sense, and you can use two-dimensional arrays to model situations that are literally two-dimensional, like a checkerboard. Let's say that you have are going to make each of your squares a member of class Panel, and now you are ready set up the entire board of 64 squares. The squares occur in eight rows of eight. Think of a single row of squares as one array. Then we want eight of those arrays:

Panel[][] square = new Panel[8][8];

If I want to talk about the entire first row of squares, I would say:

square[0]

whereas if I mean specifically the first square in the first row, I would say:

square[0][0]

And just as loops work well with one-dimensional arrays, nested loops work well with two-dimensional arrays:

for (int i = 0; i < 8; i++){

for (int j = 0; j < 8; j++){

square[i][j] = new Panel();

add(square[i][j]);

}

}



Read more about arrays: Sun Java tutorial.
Skip the section on copying arrays.
David Eck's textbook.
Skip sections 3 and 4.

Exercises

  1. What error will this code produce?

    String[] littleWord = {"in", "of", "on"};

    for (int j = 1; j < 4; j++){

    System.out.println(littleWord[j]);

    }

    }


  2. Rewrite the code in the checkerboard example to allow for the possibility that the checkerboard might change size (and not be 8 by 8 anymore).

  3. Here is the code for an applet:

    import java.applet.Applet;

    import java.awt.Color;

    import java.awt.Button;

    import java.awt.event.ActionListener;

    import java.awt.event.ActionEvent;


    public class ButtonApplet extends Applet implements ActionListener{

    Button button1 = new Button("a");

    Button button2 = new Button("b");

    Button button3 = new Button("c");

    Button button4 = new Button("d");

    Button button5 = new Button("e");

    Button button6 = new Button("f");

    Button button7 = new Button("g");


    public void init(){

    setBackground(Color.black);

    button1.setBackground(new Color(170,170,0));

    button2.setBackground(new Color(170,170,0));

    button3.setBackground(new Color(170,170,0));

    button4.setBackground(new Color(170,170,0));

    button5.setBackground(new Color(170,170,0));

    button6.setBackground(new Color(170,170,0));

    button7.setBackground(new Color(170,170,0));

    button1.addActionListener(this);

    button2.addActionListener(this);

    button3.addActionListener(this);

    button4.addActionListener(this);

    button5.addActionListener(this);

    button6.addActionListener(this);

    button7.addActionListener(this);

    add(button1);

    add(button2);

    add(button3);

    add(button4);

    add(button5);

    add(button6);

    add(button7);

    }

    public void actionPerformed(ActionEvent e){

    //what to do if the button is clicked

    }

    }

    As you can see, the author of this code seems to enjoy copying and pasting. Your task is to rewrite the code using arrays and loops, to avoid the unnecessary repetition.


Previous Topic Course Home Page Syntax Sheet Next Topic