// Zorah Fung, CSE 142 // Demo of using arrays import java.util.*; // to use the Arrays utility class public class ArraysDemo { public static void main(String[] args) { int[] a = new int[5]; // Creates an array of 5 elements. Initially filled with 0's. // Can use elements in arrays the same way we use variables a[2] = 42; // Modify element at index 2 System.out.println(a[2]); // Access element at index 2 // Similar syntax to variables. array[i] *is* a variable int x = 0; // declare integer variable int[] array = new int[10]; // declare array x = 2; // assign x to 2 array[3] = 2; // assign element at index 3 to 2 System.out.println(2 * x + 1); // use value of x in an expression System.out.println(2 * array[3] + 1); // use value of element at index 3 in an expession x = 2 * x; // reassign x to be twice as much array[3] = 2 * array[3]; // reassign element at index 3 to be twice as much. x++; // increment x array[3]++; // increment element at index 3 // Use .length property of arrays to loop over an array for (int i = 0; i < a.length; i++) { a[i] = i; } // Must use Arrays.toString to print out the contents of an array System.out.println(Arrays.toString(a)); int[] b = {0, 1, 2, 3, 4}; // Example of "quick initialization" System.out.println("a == b" + (a == b)); // Won't work System.out.println("a.equals(b)" + a.equals(b)); // Also won't work System.out.println(Arrays.equals(a, b)); // Must use Arrays class // Arrays of other types String[] groceries = {"goat cheese", "bananas", "pickles", "ham"}; groceries[0] = "cheddar cheese"; boolean[] booleanArray = new boolean[7]; // Initially all false; double[] doubleArray = new double[5]; // Initially all 0.0; // Can have array with ANY type of element. Example of Array of arrays // Anything before [] is the type of the element so "int[]" is the type // of element stored in this array. Each element is an integer array. int[][] arrayOfArrays = {{1, 2}, {3, 4, 5}, {6}, {7, 8, 9, 10}}; } }