// 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 a[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}}; } }