Arrays and Functions

Look at the following example:

import java.io.*;
public class arraydemo
{   public static void main(String args[])
    {   int size = 7
        int array3[] = {1,2,3,4,5,6,7};
        // call method to print it out
        printarray(array3, size);
     }
    public static void printarray(int array[],int size)
    {//Pre: array has values, and is size in length
     //Post: the value in array are printed to the screen
        for (int i = 0; i < size; i++)
      { System.out.print(array[i] + " ");
        }
        System.out.println();
    }
}

The printarray function was called like this: printarray(array3, size); Note that you don’t need to add the [] to the array’s name when you call the method. Many student make this mistake.

Also note the pre and post conditions on the method. All methods that have arrays as parameters should state how long the array is supposed to be and whether or not the array should be filled with values.

Finally, array’s values can change inside a method. Unlike any other parameters that we have studied, you have to be careful not to change the array’s values inside a method be accident.