// This class contains several small examples of array manipulation. Each // is written as a method. import java.util.*; public class ArraySample1 { public static void main(String[] args) { showArgs(args); // In exploring value semantics vs reference semantics, we saw that // this swap method did not change the values of x and y int x = 3; int y = 7; swap(x, y); // below is an example of an array initializer int[] list = {3, 19, 42, 73, 208, 94, 15, 5}; // we used Arrays.toString to print this array: System.out.println("list = " + Arrays.toString(list)); // we wrote a method to sum a list: System.out.println("sum of list = " + sum(list)); // we saw that the method call below changed the contents of the array destroy(list); System.out.println("after destroy, list = " + Arrays.toString(list)); // and we wrote this method for reversing the contents of the array reverse(list); System.out.println("after reverse, list = " + Arrays.toString(list)); } // method to show the contents of the "args" String array // This method only showed actual contents when we went into a terminal // window and ran the program in this way: // java ArraySample1 these words become the args public static void showArgs(String[] args) { System.out.println("args length = " + args.length); for (int i = 0; i < args.length; i++) { System.out.println("args[" + i + "] = " + args[i]); } System.out.println(); } // we saw that this is correct code for swapping two int values, but it // only swaps the local copies of these values and has no effect on any // variables that are used in calling the method public static void swap(int x, int y) { int temp = x; x = y; y = temp; } // we saw that this method was able to change the array contents because // of reference semantics public static void destroy(int[] list) { list[0] = -924; list[1] = -42; } public static int sum(int[] list) { int sum = 0; // traversal pattern for (int i = 0; i < list.length; i++) { sum += list[i]; // do something with list[i] } return sum; } // 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++) { // swap two values int temp = list[i]; list[i] = list[list.length - 1 - i]; list[list.length - 1 - i] = temp; } } }