// This program contains several examples we examined to explore arrays. import java.util.*; public class ArraySample { public static void main(String[] args) { // this is an example of a good practice problem for arrays mystery(); // example of an array initializer int[] list = {1, 7, 5, 6, 4, 14, 11}; // we have to use Arrays.toString to properly format the output System.out.println("list = " + Arrays.toString(list)); // we can pass the array as a pameter System.out.println("sum of list = " + sum(list)); // this example demonstrated that primitive values passed as a // parameter are not changed by the method because copies of the values // are passed int a = 3; int b = 5; swap(a, b); System.out.println("a = " + a + ", b = " + b); // by contrast, arrays can be changed by methods because even though // the parameter is still a copy, what is being passed is a reference // to the object change(list); System.out.println("list = " + Arrays.toString(list)); } // this method swaps the local copies of x and y, but not parameters passed // to the method public static void swap(int x, int y) { int temp = x; x = y; y = temp; } // change some values in an array public static void change(int[] list) { list[0] = -18; list[1] = -2004; } // find the sum of values in an array public static int sum(int[] list) { int sum = 0; for (int i = 0; i < list.length; i++) { // do something with list[i] // array traversal sum = sum + list[i]; } return sum; } // practice problem: what is in the array after the loop? public static void mystery() { int[] a = {1, 7, 5, 6, 4, 14, 11}; for (int i = 0; i < a.length - 1; i++) { if (a[i] > a[i + 1]) { a[i + 1] = a[i + 1] * 2; } } } }