C SC 160 Chapter 10: Arrays
major resource: An Introduction to Object-Oriented Programming with Java, fourth edition, Wu, McGraw Hill, 2006

[ previous | schedule | next ]

secondary resource: Programming and Problem Solving with Java, Slack, Brooks/Cole, 2000

Arrays

array is homogeneous ordered list of variables, accessible using integer index, with first position at index 0.

Three Steps to Using an Array

Step 1:  declare array variable

Use this format:
      type [] variable;
where type is a primitive type or name of a class and variable is identifier.
This does not create the list!  It is but a necessary first step.

example:  int [] scores;
example:  String [] names;
example:  Random [] uniRands;

Step 2:  create the list using new.

Use this format:
      variable = new type [ expression ];
where type and variable are as above, and expression evaluates to positive integer.
The array will have expression elements numbered from 0 to expression -1.

example:  scores = new int [MAX_SCORES];
example:  names = new String [MAX_NAMES];
example:  uniRands = new Random [4];

The first two steps can be combined.

example:  int [] scores = new int [MAX_SCORES];
example:  String [] names = new String [MAX_NAMES];
example:  Random [] uniRands = new Random [4];

Note:  the last statement does not create four Random objects!! It only allocates space for four references to Random objects.  The objects themselves must be created separately (see step 3).  Same for the String example, or for any other class.

Step 3: store values or references into array elements

Assign to array element as you would any other variable.

example:  scores[0] = 93;
example:  names[3] = "charlie";
example:  uniRands[0] = new Random(34829);

You can combine all three steps into one if the values are known in advance, by initializing to list of values enclosed in braces. The array size will be determined by the number of values in the list.

example:  int [] scores = { 93, 67, 78, 82, 83, 77, 74, 81, 69, 54, 90, 79 };
example:  String [] names = { "leslie", "james", "dwight", "charlie", "sarah", "bill" };
example:  Random [] uniRands = { new Random(34829), new Random(153), new Random(7643), new Random(9917) };

Arrays of objects (references)

There are examples of this above. To reiterate: creating an array does not create the individual objects to which its elements will refer! These object must be individually created using new and assigned to array elements as in Step 3 above.

Arrays and loops

Arrays and for loops were made for each other.

  int [] arr = { 27, 15, -2, 77 };
  int sum = 0;
  for (int i = 0; i < arr.length; i++) {
      sum += arr[i];
  }

Every array has a (read-only) instance variable called length whose value is the count of list elements. Its value is fixed when the array is created (see Step 2 above).

Changing the size of an array

Once the array is created (step 2 above) it cannot be changed.  You have to create another array of the desired size and copy contents from the old one to the new one.

An easy way to do this is use the System.arraycopy() method. It takes 5 parameters: name of the first array, the starting element position, name of the second array, the starting element position, and the number of elements to copy.

Example:

    int [] values = { 5, 4, 7, 6, 8, 1, 9 };
    int [] numbers = new int[values.length-2];
    System.arraycopy(values, 2, numbers, 0, values.length-2);

The numbers array is created to hold 5 values and after the array copy it will contain: 7, 6, 8, 1, 9

Assigning one array to another

Arrays are objects and array names are references, so assigning one array name to another simply results in both array names referring to the same array data (alias).  This is sometimes called a shallow copy.  To make a deep copy, use System.arraycopy() described above.

Example: "shallow copy" through assignment

    int [] values = { 5, 4, 7, 6, 8, 1, 9 };
    int [] numbers;
    numbers = values;
    numbers[4] = 3;
    System.out.println(values[4]);

The output of this code segment is 3, not 8! After the array assignment numbers = values; both array names refer to the same list of values. This reinforces the concept of arrays as objects.

Passing arrays as parameters

Example:  Notice how the parameters and arguments for twister are configured. What is the output of this code?

public class Twist {

   static void twister(int a, int[] arr) {
      a = 4;
      arr[0] = arr[3];
   }
   public static void main(String[] args) {
      int [] num = { 1, 2, 3, 4 };
      int [] value = { 27, 15, -2, 77 };
      for (int i = 0; i < num.length; i++) {
         System.out.println(num[i] + ": "+value[i]);
      }
      System.out.println();
      twister(num[0], value);   // <--- method is invoked here
      for (int i = 0; i < num.length; i++) {
         System.out.println(num[i] + ": "+value[i]);
      }
   }
}

Two-dimensional arrays

Suppose each element of an array were itself an array?

Here is a conceptual storage view of a 3 x 4 array, as defined by:

int [][] grid = new int[3][4];
 grid[0][0]   grid[0][1]   grid[0][2]   grid[0][3] 
 grid[1][0]   grid[1][1]   grid[1][2]   grid[1][3] 
 grid[2][0]   grid[2][1]   grid[2][2]   grid[2][3] 

Initialization lists for 2-D arrays

If you want to do initialization at definition time, then use a list of nested lists.

int [][] grid = {  { 0, 1, 2, 3 },
                   { 4, 5, 6, 7 },
                   { 8, 9,10,11 } };
 

2-D Arrays and nested loops

2-D Arrays and nested for loops were made for each other.

What is the output of this program?

public class TwoDimTest {
   public static void main(String[] args) {
      int [][] grid = {  { 0, 1, 2, 3 },
                         { 4, 5, 6, 7 },
                         { 8, 9,10,11 } };
      for (int row = 0; row < grid.length; row++) {
         for (int col = 0; col < grid[row].length; col++) {
           System.out.print(grid[row][col] + " ");
         }
         System.out.println();
      }
   }
}

If you notice how the length variable is handled, you'll see this example reinforces the notion that a 2-D array is an array of arrays.

Optional Topic: Non-rectangular 2-D arrays

Because a 2-D array is an array of arrays, it can be an array of unequal-size arrays.  This is easily demonstrated from the previous example by changing the length of the initialization lists, as shown in bold.

public class TwoDimTest {
   public static void main(String[] args) {
      int [][] grid = {  { 0, 1, 2, 3 },  // first row has 4 columns
                         { 4, 5, 6 },     // second row has 3 columns
                         { 7, 8, 9, 10, 11 } };  // third row has 5 columns
      // the loop works without alteration!
      for (int row = 0; row < grid.length; row++) {
         for (int col = 0; col < grid[row].length; col++) {
           System.out.print(grid[row][col] + " ");
         }
         System.out.println();
      }
   }
}

Note: If you used the 3-step method of creating and filling this array, the first two steps would look something like this:

      int [][] grid;
      grid = new int[3][]; // create rows but not columns
      grid[0] = new int[4]; // create 4 columns for first row
      grid[1] = new int[3]; // create 3 columns for second row
      grid[2] = new int[5]; // create 5 columns for third row

The third step, assigning values to the array elements, is not shown here. Once this is done, the for loop would be the same.

Optional Topic: Arrays of more than 2 dimensions

Since a 2-D array is an array of 1-D arrays, is there any reason we can't define a 3-D array to be an array of 2-D arrays?
In this example, I call the third dimension "page" analogous to a worksheet in a spreadsheet file.

public class ThreeDimTest {
   public static void main(String[] args) {
      int [][][] threeD = { {  {0,1},  {2,3},   {4,5}  },
                            {  {6,7},  {8,9},   {10,11}},
                            { {12,13}, {14,15}, {16,17}},
                            { {18,19}, {20,21}, {22,23}} };
      for (int row = 0; row < threeD.length; row++) {
         for (int col = 0; col < threeD[row].length; col++) {
            for (int page = 0; page < threeD[row][col].length; page++) {
               System.out.print("threeD["+row+"]["+col+"]["+page+"] = ");
               System.out.println(threeD[row][col][page] );
            }
         }
      }
   }
}

Conceptually, there is no limit to the number of dimensions.  This is in clear contrast to most earlier programming languages, which supported multidimensional arrays up to a fixed limit (2 or 3 or 6) because in those languages a multidimsional array was fundamentally different than a 1-D array.


[ C SC 160 | Peter Sanderson | Math Sciences server  | Math Sciences home page | Otterbein ]

Last updated:
Peter Sanderson (PSanderson@otterbein.edu)