Java Arrays [Lists] in 10 Minutes Declaring an array (and its types) int[] myIntArray; double[] myDoubleArray; String[] myStrings; //What’s the pattern? //dataType[] arrayName; //Note: the arrays don’t really exist yet! Initializing an array int[] myIntArray = new int[4]; double[] myDoubleArray = new double[5]; String[] myStrings = new String[3]; //What’s the pattern? //dataType[] arrayName = new dataType[size]; //Now we’ve allocated new space for the arrays //Each array element has a default 0 value Explicit initialization //or we can explicitly initialize the arrays int[] myIntArray = { 4, 2, 6, 8 }; double[] myDoubleArray = { 1.0, 2.3, 6.3, 7.5, 0.1 }; String[] myStrings = {“lol”,“omg”,“ROTFLSHMSFOAIDMT”} //Note: use { } and separate elements with commas Size/length of an array int[] myIntArray = { 4, 2, 6, 8 }; System.out.println( myIntArray.length ); //prints 4 //Note: length has no () with arrays!!!! Accessing an array element int[] myIntArray = { 4, 2, 6, 8 }; System.out.print( myIntArray[0] ); //prints 4 System.out.print( myIntArray[2] ); //prints 6 System.out.print( myIntArray[myIntArray.length-1] ); //prints 8 //Each element in the array has an index //Indices start at 0 and end at length-1 Changing/setting an array element int[] myIntArray = { 4, 2, 6, 8 }; myIntArray[0] = 9; //myIntArray now has [9, 2, 6, 8] myIntArray[1] = myIntArray[2]; //myIntArray now has [9, 6, 6, 8] Loops and arrays //Example of linear traversal of array int[] myIntArray = { 4, 2, 6, 8 }; for (int i = 0; i < myIntArray.length; i++) { System.out.println(myIntArray[i]); } //Try out on your own the same loop and print out all the words in: String[] myStrings = {“lol”,“omg”,“ROTFLSHMSFOAIDMT”} Initialize array elements with a loop //Traverse the array and set each element to 3 int[] myIntArray = { 4, 2, 6, 8 }; for (int i = 0; i < myIntArray.length; i++) { myIntArray[i] = 3; } Reference variables Array variables are actually references to the arrays Example: int[] myIntArray = new int[4]; int[] array2 = myIntArray; //How many arrays are there? (Hint: How many times did we say “new”? //How many array references are there? (Hint: How many times did we say “int[]”? Reference Variables cont’d int[] myIntArray = { 4, 2, 6, 8 }; int[] array2 = myIntArray; array2[0] = 0; System.out.print(myIntArray[0]); //prints 0 //myIntArray and array2 “refer” to the same array