Passing an object or an array to a method

 

Overview

Just as a primitive value may be passed to a method, an object or an array may be passed to a method. Because an array is an object in Java, the technique for passing arrays and objects is very similar. They are both passed by reference.

 

Passing an object by reference

public static void show(String theString)

where theString is the local object reference for accessing the String object within the show() method. The calling method, of course, must pass a parameter of the correct type. To call the show() method, the following would be a valid statement

show("Here's a string!"); 

In the small program

public class App {
  public static void main (String[] args) {
    String x = new String("Hello World!");
    show(x);
  }
  public static void show(String theString) {
    System.out.println(theString);
  }
}

The show() method receives a reference to the String object of the main() method as shown by the following diagram:

main() method

show() method

x

theString

 

----->

"Hello World!"

<-----

 

When the show() method ends, the duplicate reference is garbage collected but the String object remains.

The previous example would not permit the object to be changed because a String object is immutable. But the following demonstrates how a called method can change the contents of an object it receives by reference.

public class App {
  public static void main (String[] args) {
    StringBuffer x = new StringBuffer("Hello World!");
    flip(x);
    System.out.println(x.toString());
  }
  public static void flip(StringBuffer theString) {
    theString.reverse();
  }
}

Even though the flip() method doesn't return a value, it has altered the contents of the shared object. 

 

Passing an array

Note that [] is coded in the method header and NOT in the call statement.

For example, the reset() method of the following program receives an array by reference and sets every element to zero. Upon return to the calling method, the 0 values are displayed.

public class App {
  public static void main (String[] args) {
    int[] values = {1, 2, 3};
    reset(values);
    for (int i = 0; i < values.length; i++) {
      System.out.println(values[i]);
    }
  }
  public static void reset(int[] theArray) {
    for (int i = 0; i < theArray.length; i++) {
      theArray[i] = 0;
    }
  }
}

 

Returning an object or an array from a method

public static String readString()

- returns a String object to the caller.

public static char[] getChars()

- returns a char array to the caller.

public static String[] getStrings()

- returns an array of String object references to the caller.

return "All done";

would be a valid return statement for a method that must return a String object.

 

Sample program

This is a modified version of the sample from the previous lesson. It 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.

It contains class methods to display the array of names and to sort the array of names into alphabetical order.

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;

      // 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.");

      // Display the array of names.

      System.out.println("\tThe unsorted array contains:");
      Utility.skip();
      showStrings(names);

      // Sort the array and save the number of passes required.

      int n = sortStrings(names);

      // Display the sort statistics.

      Utility.skip();
      System.out.println("\tSort required " + n + " pass(es).");

      // Display the sorted array of names.

      System.out.println("\tThe sorted array contains:");
      Utility.skip();
      showStrings(names);

      // 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();
    }
  }

  // This method loops to display each element in an array of String
  // objects.

  public static void showStrings(String[] theArray) {

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

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

  // This method will sort an array of String objects into alphabetical
  // order. It receives the array by reference and returns an int that
  // indicates how many passes were required to sort the array.

  public static int sortStrings(String[] theArray) {

    // Local variables.

    boolean didSwap;
    int sortPasses = 0;

    // 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.

    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 < theArray.length - 1; i++) {

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

        if (theArray[i + 1].compareTo(theArray[i]) < 0) {
          String temp = theArray[i];
          theArray[i] = theArray[i + 1];
          theArray[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);

    // Exit by returning the number of passes required.

    return sortPasses;
  }
}

Note: The sortStrings() method is extremely generic and can be used to sort any array of strings into alphabetical order.

 

More information

Java ranch has an excellent "campfire story" relating to this lesson. Be sure to read Pass-by-Value Please.

 

Review questions

  1. True or False: A method whose header is

public static int[] get()

may be called with the statement

int x = get();

  1. True

  2. False

  1. What will result from attempting to compile and execute the following program? The line numbers are for reference purposes only.

1
2
3
4
5
6
7
8
9
10
public class App {
  public static void main (String[] args) {
    String x = "xyz";
    doIt(x);
    System.out.println(x);
  }
  public static void doIt(String arg) {
    arg = "abc";
  }
}
  1. Compilation will fail at line 4

  2. Compilation will fail at line 8

  3. Compilation will succeed but a runtime error will occur

  4. Compiles and runs to display "xyz"

  5. Compiles and runs to display "abc"

  1. What will result from attempting to compile and execute the following program? The line numbers are for reference purposes only.

1
2
3
4
5
6
7
8
9
10
11
public class App {
  public static void main (String[] args) {
    char[] letters = {'x', 'y', 'z'};
    letters = getThem();
    System.out.println("Character: " + letters[3]);
  }
  public static char[] getThem() {
    char[] them = {'a', 'b', 'c', 'd'};
    return them;
  }
}
  1. Compilation will fail at line 4

  2. Compilation will fail at line 9

  3. Compilation will succeed but a runtime error will occur at line 5

  4. Compiles and runs to display "Character: z"

  5. Compiles and runs to display "Character: d"

  1. What will result from attempting to compile and execute the following program? The line numbers are for reference purposes only.

1
2
3
4
5
6
7
8
9
10
11
12
public class App {
  public static void main (String[] args) {
    short[] numbers = {1, 2, 3};
    System.out.println("Sum: " + sum(numbers));
  }
  public static double sum(double[] array) {
    double tally = 0;
    for (int i = 0; i < array.length; i++)
      tally += array[i];
    return tally;
  }
}
  1. Compilation will fail at line 3

  2. Compilation will fail at line 4

  3. Compilation will succeed but a runtime error will occur at line 4

  4. Compiles and runs to display "Sum: 6"

  5. Compiles and runs to display "Sum: 6.0"