//This file has several exmaples of methods being used on // an array of primes import java.util.*; public class PrimesArray { public static void main(String[] args){ int[] primes = {2, 3, 5, 7, 11, 13, 17, 19, 23}; // find the sum of the array elements and print it int sumOfPrimes = sum(primes); System.out.println("Sum was: " + sumOfPrimes); System.out.println(); //printing System.out.println("Printing the array"); // not good default printing System.out.println(primes); // custom printing method printArray(primes); // Java util helper method for printing System.out.println(Arrays.toString(primes)); System.out.println(); // reverse System.out.println("Reversing the array"); reverse(primes); System.out.println(Arrays.toString(primes)); System.out.println(); // evil print (it changes the array when it prints it) System.out.println("Evil print"); evilPrintArray(primes); evilPrintArray(primes); } // This method takes an int[] and finds the sum of all the // elements. It returns the sum. public static int sum(int[] a){ int sum = 0; for(int i = 0; i < a.length; i++){ sum += a[i]; } return sum; } // This method takes an int[] and prints it out. public static void printArray(int[] a){ System.out.print("[" + a[0]); for(int i = 1; i < a.length; i++){ System.out.print(", " + a[i] ); } System.out.println("]"); } // This method takes an int[] and prints it out. // It also, unexpectedly, changes the array it was given. public static void evilPrintArray(int[] a){ System.out.print("[" + a[0]); for(int i = 1; i < a.length; i++){ System.out.print(", " + a[i] ); } System.out.println("]"); a[0] = -32847; } // This method takes an int[] and reverses the elements in // the array. It doesn't return anything since it modifies // the array that was passed in. public static void reverse(int[] a){ for(int i = 0; i < a.length / 2; i++){ int temp = a[i]; a[i] = a[a.length - 1 - i]; a[a.length - 1 - i] = temp; } } }