/** An Example of some array manipulation **/ public class ArrayExample { public static void main (String args[]) { int numberOfElements = 0; if (args.length > 0) { // Use value from command line numberOfElements = Integer.parseInt(args[0]); } ArrayExample anExample = new ArrayExample(); anExample.initializeArray(numberOfElements); // Notice that method calls can be included in other method // calls: in this case, returning primitive values that will // be converted to String objects. System.out.println("sum = " + anExample.Sum() + " average = " + anExample.Average() ); } private int[] intArray; // all instance (non static) methods // have acess to this 'instance' variable /** Initialize the array (which will be made big enough to hold size entries) contents with some numbers */ public void initializeArray(int size) { intArray = new int[size]; int startValue = size * 3; // pick any number for (int i = 0; i < intArray.length; i++) { intArray[i] = startValue; // put current number in next slot startValue = startValue - 2; // and calculate next number } } /** Calculate the sum of the array contents */ public long Sum() { int index; int arrayLen; long sum = 0; // All arrays have a length field that specifies how many // elements the array contains arrayLen = intArray.length; // Calculate the sum the values in all array elements for (index = 0; index < arrayLen; index++) { sum += intArray[index]; } return sum; } /** Calculate the average of the array contents */ public double Average() { // Notice that Average calls Sum() to total the values in the // array, rather than duplicating that calculation here. What // is going on with the "(double)" ? double average = (double) Sum() / intArray.length; return average; } }