Introduction: 6.1.0

  • An array is a block or memory which stores elements of data items of the same type under one name
    • Useful when you have many elements of the same type to keep track of together
    • Each item is stored at an index
      • Like a locker number
      • start from index 0

Declaring and Creating an Array: 6.1.1

  • To make a variable into an array, put square brackets after the data type
    • int[] testScores
      • An array called testScores which is an array of integers
  • Arrays are objects
    • A variable that declares an array holds a reference to the object
      • An uninitialized array is null!
  • You can initialize an array using the keyword new or an initalizer list
int[] myArray = new int[6];
int[] yourArray = {3, 4, 5, 6, 7, 8};

int[] theirArray;
theirArray = new int[6];

Using new to Create arrays: 6.1.2

  • To create an empty array after declaring a variable, use the new keyword with the type and size of the array
    • This actually creates the array in memory
  • Array elements are initialized as normal
    • Primitives get their normal default values
    • Objects become null

Initializer Lists to Create Arrays: 6.1.3

  • Initialize arrays using an initializer list
    • Initialize values of an array to a list of values in curly brackets
    • Don’t specify the size
    • Primitive type arrays store the values themselves
    • Object type arrays store object references

Array Length: 6.1.4

  • Arrays know their length
    • Available with arrayName.length

Access and Modify Array Values: 6.1.5

  • To access array items, use an indexed array variable
    • array name and index inside of square brackets
    • index is the position of an item in an array
int[] myArray = {0, 1, 2};
myArray[1] = 17; // myArray == {0, 17, 2};
  • to keep track of 5 highest scores in a game with the person who got them, you could use two parallel arrays
    • You need to make sure they stay synchronized!
  • If you try to access an element which doesn’t exist, java throws an ArrayOutOfBoundsException
  • You can use variables for array indexes
int index = 7;
myScore = scores[index];

Summary: 6.1.7

  • Arrays are collections of related data of all the same data type
  • The size of an array is established at the time of creation
    • this size is fixed!
  • Arrays can store primitive data or object reference types
  • When an array is created with new all elements are initialized to null or default primitive values
  • Initializer lists can be used to create and initialize arrays
  • Square brackets are used to access and modify elements in an array with an index
  • Indices range from [0, arr.length - 1]
    • Anything outside of that throws an ArrayIndexOutOfBoundsException