next up previous
Next: Parameters passed to a Up: Unit 07 Previous: Example: search of the

Example: inverting the contents of an array

We develop a static method invertArray() that takes as parameter an array of integers and modifies it by inverting the order of its elements (the first one becomes the last one, the second one the last but one, etc.):

public void invertArray(int[] v) {
  for (int i = 0; i < v.length/2; i++) {
    int temp;
    temp = v[i];
    v[i] = v[v.length-1-i];
    v[v.length-1-i] = temp;
  }
}

Example of usage:

public static void main(String[] args) {
  int[] x = { 5, 3, 9, 5, 12};    // creation of an array x of 5 int
  for (int i = 0; i < 5; i++)     // prints out 5 3 9 5 12
    System.out.println(x[i]);
  invertArray(x);                 // inverts the array x
  for (int i = 0; i < 5; i++)     // prints out 12 5 9 3 5
    System.out.println(x[i]);
}

Notice that, when the array x is passed as an actual parameter to the method invertArray(), the formal parameter v refers to the same array object to which x refers. Hence, all modifications done to the array inside the method are done on the same array to which x refers, and hence will be visible to the calling method (in this case, main()).


next up previous
Next: Parameters passed to a Up: Unit 07 Previous: Example: search of the