Arrays


Arrays

An array is an object that contains a collection of numbered variables. Each array has a size telling how many variables it holds. The variables are numbered starting at 0. For example, the following is a picture of an array object that holds four variables, numbered from 0 to 3, where each variable contains 0.

You refer to variable number n in array A as A[n]. For example, W[2] is the variable with index 2 in array W and frog[5] is the variable with index 5 in array frog. If kangaroo is an array whose variables hold integers, then statement

  kangaroo[1] = 25;
stores 25 into variable number 1 in that array.

You are only allowed to use variables that exist. If array fish has just 4 variables (numbered from 0 to 3) then asking for fish[4], which does not exist, throws exception ArrayIndexOutOfBoundsException.


Array types and array variables

Generally, if A is an array whose numbered variables each holds a value or object of type or class T, then A has type T[]. For example, an array of ints has type int[], an array of doubles has type double[] and an array of strings has type String[]. To create an array variable, write the array type followed by the array name. For example,

  int[] poodle;
creates a new variable called poodle of type int[].

Arrays are objects, so a variable can only hold a reference to an array. Creating an array variable does not create an array object. That needs to be done separately. Also, two array variables can refer to the same array object. The next section shows how to create an array object.


Creating arrays

Expression new int[12] yields, as its result, a newly created array object of 12 variables, each of type int. You typically store a reference to the new array object into a variable.

  int[] beagle = new int[12];
Similarly, expression new double[80] yields a new array of 80 variables, each having type double, and expression new String[500] yields a new array object with 500 String variables in it. For example, you might say
  int numNames = 500;
  String[] names = new String[numNames];
to create an array of strings and store a reference to it into variable names.

When you create an array of type int[] or long[] or double[], each variable in the array starts out with value 0. A new array of type boolean[] has all of its variables initially set to hold false, and a new array of type char[] has its variables initially set to a special character '\0', which is an unprintable character. (You won't find it on your keyboard.)

If C is any class then a new array of type C[] is initialized so that all of its variables contain null. For example, all of the variables in a new array of Strings will start out holding null.


Doing things with arrays

Suppose that you want to create a new array of 20 integers and make all of the variables in the array hold 1. The following does the job.

  int[] arr = new int[20];
  int n = 0;
  while(n < 20)
  {
    A[n] = 1;
    n++;
  }

You use an array to remember some information. As a simple (and somewhat silly) example, suppose that you want to read a sequence of nonzero integers from the keyboard and then write them out backwards afterwards. The last number is 0, which only serves as an end marker, and is not to be written. For example, if the user types

15
65
7
0
the the program responds by displaying
7
65
15
Here is a program fragment that does the job. It reads the numbers and stores them into an array. When it sees the end marker (0), it goes back through the array, writing the numbers that it has stored. Assume that there are no more then 200 numbers.

  int[] data = new int[200];
  Scanner keyboard = new Scanner(System.in);

  //-------------------------------------------------
  // Read the numbers.
  //-------------------------------------------------

  int n = 0, num = 0;
  while(n < 200 && keyboard.hasNextInt())
  {
    num = keyboard.nextInt();
    if(num == 0) break;
    data[n] = num;
    n++;
  }

  //-------------------------------------------------
  // If we ran out of room, say so.  Otherwise, show
  // the numbers backwards (by counting down).
  //-------------------------------------------------

  if(num != 0) 
  {
    System.out.println("I ran out of room.");
  }
  else 
  {
    int k = n - 1;
    while(k >= 0)
    {
      System.out.println(data[k]);
      k--;
    }
  }

A common mistake with arrays

Be careful to think out what you are doing with arrays. A common mistake is to write A[n] where you really meant to write n, or to write n where you really meant to write A[n].

If you want to talk about a value stored in array A, write A[n], where n tells which one you want. If you want to talk about a particular index n, write n.

For example, it would be a mistake to replace line

  while(n < 200 && keyboard.hasNextInt())
in the above program fragment by
  while(data[n] < 200 && keyboard.hasNextInt())
A simple sanity check usually suffices to catch such errors. Why do I care whether one of the data values is less than 200? So why am I asking that?


Getting the size of an array

You can ask an array object how large it is. If variable A refers to an array object then A.length is the total number of variables in array A.

Notice that getting the length of an array is a little different from getting the length of a string. If s is a string, then the length of s is s.length( ). But if a is an array, then the size of array a is a.length. You write an empty set of parentheses after length for a string, but not for an array.

Be a little cautious about using a.length. What that tells you is the total number of variables in the array. That is not always what you want. Often, you create an array that is a little larger than what you need, simply because you do not yet know just how much room you will need in the future. If only part of the array ends up holding information, then the size that you want is the amount of the array that is occupied, not the amount of space that is available. For example, the example above that reads up to 200 numbers from the keyboard does not necessarily read exactly 200 numbers. That is just an upper limit. When it prints the contents of the array, it shows n values, not 200 values.

The total number of variables in array a is called the physical size of the array. The total number of variables that are currently in use is called the logical size of the array. Be sure not to get the two confused with one another.


Additional information

Savitch and Carrano discuss arrays in Chapter 7.

Problems

  1. [solve] Write a Java statement that creates a variable called pheasant that refers to an array of 25 integers.

  2. [solve] Write a Java statement that creates a variable called pigeon that refers to an array of 60 real numbers (type double).

  3. [solve] Is it allowed to write statement

      int[] penguin;
    
    without creating an array for penguin to refer to?

  4. [solve] Do a careful hand simulation of the following. What are A[0], A[1], A[2] and A[3] after it is finished?

      int A = new int[4];
      int k = 0;
      while(k < 4)
      {
        A[k] = k;
        k++;
      }
      k = 1;
      while(k < 4)
      {
        A[k] = A[k-1] - 1;
        k++;
      }
    

  5. [solve] What happens when the following is run?

      int[] fox = new int[5];
      int n = 1;
      while(n <= 5)
      {
        fox[n] = n;
        n++;
      }
    


Summary

An array is a collection of numbered variables. You refer to variable number n in array A as A[n].

Remember that the variables in an array are numbered starting at 0. If A contains 5 variables, then they are A[0], A[1], A[2], A[3] and A[4].

An array is an object, and a variable can refer to an array. When you declare a variable that can refer to an array of ints, say that the array variable has type int[]. Generally, add [] after a type to indicate an array of those. Expression A.length yields the number of variables in array A, also called the physical size of A.

You will not typically find yourself writing the word array in a Java program. To create a new array of 50 integers called clock, use

  int[] clock = new int[50];
You do not write
  int[] clock = new array[50];