Initializing and processing arrays of objects

 

Overview

Java requires that all the elements within an array be of the same type. In the previous lesson, we constructed arrays in which all the elements were of the same primitive type (boolean, float, char, etc.).

In this lesson, we will construct arrays in which all the elements are of the same non-primitive, class type (such as String or StringBuffer). Such arrays are called object arrays.

 

Object arrays

String[] names = new String[5];

Constructs an array of 5 String object references. It is important to understand that no String objects are created by this declaration. We have simply created an array of null object references which may later be assigned to individual String objects (as shown by the following diagram).

names

Heap space

  
  
  
  
  

----->

  
  
  
  

null

null

null

null

null

  
  
  
  
  
  
  
  
  
  

The statement

names[3] = new String("Hello World!");

would instantiate a String object and assign it to the fourth element in the names array (which would look like the following).

names

Heap space

  
  
  
  
  

----->

  
  
  
  

null

null

null

  

null

  
  
  

----->

  
  
  
  

"Hello World!"

  

To display the value of this particular String object, one might code

System.out.println(names[3]);

which retrieves the String object referenced by the fourth element in the names array.

array-identifier[index].method-name(arguments)

For example, to determine the length of the encapsulated string in the fourth element of the names array one would code the expression

names[3].length()

Example: Attempting to call an instance method of an object that doesn't exist.

public class App {
  public static void main(String[] args) {
    String[] names = new String[5];
    System.out.println("Length of first string: " + names[0].length());
  }
}

String aString = new String("def");
String[] x = {new String("abc"), aString, "xyz"};

creates a three element array of String object references. The first element references a String object having the value "abc", the second element references a String object having the value "def", and the third references the String object in the literal pool having the value "xyz".

 

Sample program

The following program allows a user to specify the number of elements and element values for an array of String objects where each object encapsulates a person's name. After all names have been entered, they are displayed in their original order. The array is then sorted into the alphabetical order of the names being referenced and the sorted list of names is displayed. The user is then asked if they want to do another array.

public class App {
  public static void main(String[] args) {

    // Loop control variable.

    char again = 'y';

    // Main loop. One array is entered and processed in each iteration.

another:

    while (again == 'Y' || again =='y') {

      // Local variables for performing array processing.

      String[] names;
      int noElements;
      boolean didSwap;
      int sortPasses;

      // Prompt for and read how many names the array is to contain.

      Utility.separator(40, '=');
      System.out.print("How many names will you enter? " );
      noElements = Keyboard.readInt();

      // If the number of elements is invalid, display an error message
      // and continue the main loop from the beginning.

      if (noElements <= 0) {
        Utility.skip();
        System.out.println("\tInvalid number of elements");
        continue another;
      }

      // Instantiate the array and loop to load its elements with values
      // entered by the user.

      names = new String[noElements];
      Utility.skip();
      for (int i = 0; i < noElements; i++) {
        System.out.print("Element (" + i + "): ");
        names[i] = Keyboard.readString();
      }

      // Display a message saying that loading is complete.

      Utility.skip();
      System.out.println("\tLoading is complete.");
      System.out.println("\tThe unsorted array contains:");
      Utility.skip();

      // Loop through the entire array to display the value of each
      // element.

      for (int i = 0; i < noElements; i++) {
        System.out.println("\t\t" + names[i]);
      }

      // Sort the array. This is accomplished by passing through the
      // entire array comparing adjacent element values. If the second
      // of the two elements should come first, they are swapped and an
      // indicator set that specifies that a swap occurred. Additional
      // passes are made until no swap occurs.

      sortPasses = 0;
      do {

        // When a new pass begins, no swap has occurred.

        didSwap = false;

        // Loop through the entire array to compare adjacent elements.

        for (int i = 0; i < names.length - 1; i++) {

          // If the second of the two elements should come first,
          // swap them and indicate that a swap occurred.

          if (names[i + 1].compareTo(names[i]) < 0) {
            String temp = names[i];
            names[i] = names[i + 1];
            names[i + 1] = temp;
            didSwap = true;
          }
        }

        // Increment the counter of the number of sort passes and
        // continue looping as long as a swap occurred.

        sortPasses++;
      } while (didSwap);

      // Display sort statistics.

      Utility.skip();
      System.out.println("\tSort required " + sortPasses + " pass(es).");
      System.out.println("\tThe sorted array contains:");
      Utility.skip();

      // Display the sorted array's contents by looping through the
      // entire array to display the value of each element.

      for (int i = 0; i < noElements; i++) {
        System.out.println("\t\t" + names[i]);
      }

      // Ask the user if they want to do it again and repeat the loop as
      // requested.

      Utility.separator(40, '=');
      System.out.print("Again? (Y/N): ");
      again = Keyboard.readChar();
    }
  }
}

Note: There are many sorting techniques. The one shown here is not necessarily the best, but is fairly straightforward.

 

Lab exercise for Ferris students

E-mail your answers to this assignment no later than the due date listed in the class schedule.

 

Review questions

  1. Which of the statements below are true after executing the following?  (choose three)

String[] s = new String[10];

  1. s.length is 10

  2. s[0] is null

  3. s[0].length() is 0

  4. s[0] == s[1]

  5. s[0].equals(s[1])

  1. Assuming that all unseen code is correct, what will result from attempting to compile and execute the following code? The line numbers are for reference purposes only.

1
2
3
4
5
String[] x = {"a", "bc", "def"};
if (x.length == x[2].length())
  System.out.println("equal");
else
  System.out.println("not equal");
  1. Compilation will fail at line 1

  2. Compilation will fail at line 2

  3. Compilation will succeed but a runtime error will occur

  4. Compiles and runs to display "equal"

  5. Compiles and runs to display "not equal"

  1. How many objects are created by the following statement?

StringBuffer[] zBuffers = new StringBuffer[10];

  1. none

  2. one

  3. ten

  4. eleven

  1. Assume that table is an array of String object references where no element is null (each element references an instantiated String object). Code a single statement to extract the first character of the first String object referenced by the array and assign it to a previously defined char variable named first.