Introduction: 6.5.0

  • An array is consecutive storage for multiple items of the same type
    • The first index is 0

Concept Summary: 6.5.1

  • Array
    • An array can hold many items (elements) of the same type.
    • You can access an item (element) at an index and set an item (element) at an index.
  • Array Declaration
    • To declare an array specify the type of elements that will be stored in the array, then ([]) to show that it is an array of that type, then at least one space, and then a name for the array.
    • int[] highScores String[] names
  • Array Creation
    • To create an array type the name and an equals sign then use the new keyword, followed by a space, then the type, and then in square brackets the size of the array (the number of elements it can hold
    • names = new String[5];
  • Array Index
    • You can access and set values in an array using an index. The first element in an array called arr is at index 0 arr[0]. The last element in an array is at the length minus one - arr[arr.length - 1].
  • Array Initialization
    • You can also initialize (set) the values in the array when you create it. In this case you don’t need to specify the size of the array, it will be determined from the number of values that you specify.
    • int[] highScores = {99,98,98,88,68};
  • Array Length
    • The length of an array is the number of elements it can hold. Use the public length field to get the length of the array.
    • given int[] scores = {1,2,2,1,3,1};, scores.length equals 6.
  • Element Reference
    • A specific element can be referenced by using the name of the array and the element’s index in square brackets. Example: scores[3] will return the 4th element (since index starts at 0, not 1). To reference the last element in an array, use array[array.length - 1]
  • For-each Loop
    • Used to loop through all elements of an array. Each time through the loop the loop variable will be the next element in the array starting with the element at index 0, then index 1, then index 2, etc.
  • Out of Bounds Exception
    • An error that means that you tried to access an element of the array that doesn’t exist maybe by doing arr[arr.length]. The first valid indices is 0 and the last is the length minus one.

Java Keywords: 6.5.2

  • for
    • starts a for loop (general and for-each)
    • Syntax for for-each is for (type var : array)
  • static
    • Used to create a class method
      • A methoc which can be called using the class name
        • Math.abs(-3)

Common Mistakes: 6.5.4

  • forgetting to create an array; only declaring it
  • using 1 as the first index
    • it should be 0!
  • using array.length as the last valid index in an array
    • is array.length - 1
  • using array.length() instead of array.length
  • using array.get(0) instead of array[0]
  • going out of bounds when looping an array
  • jumping out of a loop too early before all values have been processed