Declaring and using array Array of objects Sorting and seaching elements in an array Two-dimensional array The ArrayList class 2 .Array • An array is a data structure that stores a collection of | Arrays Chapter 5 Outline Declaring and using array Array of objects Sorting and seaching elements in an array Two-dimensional array The ArrayList class Array An array is a data structure that stores a collection of values of the same type Arrays are accessed with [ ] Array indices are zero-based Example: scores[5] returns the 5th value in the array 0 1 2 3 4 5 6 7 8 9 79 87 94 82 67 98 87 81 74 91 scores The entire array has a single name Each value has an index Declaring an array Syntax: Example: int[] scores = new int[100]; an array that can hold 100 integers String[] names; names = new names[20]; an array that can hold 20 String objects You can create an array object and supply initial values at the same time int[] smallPrimes = { 2, 3, 5, 7, 11, 13 }; char[] letterGrades = {A, B, C, D, ’F}; DataType[] arrayName = new DataType[size]; DataType[] arrayName; // only declares the variable arrayName = new DataType[size]; See ebook page 328 for other syntax Note that | Arrays Chapter 5 Outline Declaring and using array Array of objects Sorting and seaching elements in an array Two-dimensional array The ArrayList class Array An array is a data structure that stores a collection of values of the same type Arrays are accessed with [ ] Array indices are zero-based Example: scores[5] returns the 5th value in the array 0 1 2 3 4 5 6 7 8 9 79 87 94 82 67 98 87 81 74 91 scores The entire array has a single name Each value has an index Declaring an array Syntax: Example: int[] scores = new int[100]; an array that can hold 100 integers String[] names; names = new names[20]; an array that can hold 20 String objects You can create an array object and supply initial values at the same time int[] smallPrimes = { 2, 3, 5, 7, 11, 13 }; char[] letterGrades = {A, B, C, D, ’F}; DataType[] arrayName = new DataType[size]; DataType[] arrayName; // only declares the variable arrayName = new DataType[size]; See ebook page 328 for other syntax Note that when an initializer list is used: the new operator is not used no size value is specified Using the array If a is an array, to process all elements in a, using: Example: for (int i=0; i traverse the entire collection Bounds checking Once an array is created, it has a fixed size The index value must be in range 0 to N-1, so you cannot access indexes outside this limit The Java interpreter throws an exception named ArrayIndexOutOfBoundsException if an array index is out of bounds This is called automatic bounds checking It’s common error when using arrays: for (int i=0; i Array as .