// This program contains several examples we examined to explore arrays. import java.util.*; public class ArraySample { public static void main(String[] args) { // below are two examples of an array initializer int[] primes = {2, 3, 5, 7, 11, 13, 17, 19, 23}; String[] words = {"four", "score", "and", "seven", "years", "ago"}; // we have to use Arrays.toString to properly format the output System.out.println("primes = " + Arrays.toString(primes)); // we wrote a method to sum a list: System.out.println("sum of primes = " + sum(primes)); // 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); // we saw that we can have two variables that both refer to the same // array object: int[] list1 = {8, 17, 4, 93}; int[] list2 = list1; list2[0] = -98; System.out.println("list1 = " + Arrays.toString(list1)); // notice that list1 has changed even though we changed list2[0] // we saw that the method call below changed the contents of the array change(list1); System.out.println("list = " + Arrays.toString(list1)); // and we wrote this method for reversing the contents of the array reverse(primes); System.out.println("after reverse, primes = " + Arrays.toString(primes)); // this is an example of a good practice problem for arrays mystery(); } // 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; } // change some values in an array public static void change(int[] list) { list[0] = -18; list[1] = -2004; } // 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; } // this method reverses the sequence of values in an array public static void reverse(int[] list) { // we found that we only wanted to do the swapping for half of the // length of the list (otherwise we unreversed it) for (int i = 0; i < list.length / 2; i++) { // compute the index for the other value to swap int j = list.length - 1 - i; // swap two values int temp = list[i]; list[i] = list[j]; list[j] = temp; } } // 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; } } } }