Arrays

Arrays are containers that can hold multiple values of the same data type.

Declaring Arrays

We can declare a reference to an array as follows.  These statements don’t, however, allocate memory for the array.

String args[];
String[] args;

int heights[];
int[] heights;

Allocating Arrays

In order to allocate space you need to use the new keyword and specify either the size or a list of initial elements.

String[] arr1 = new String[3];  // elements initialized to null
int[] arr2 = new int[12];       // elements initialized to 0

String s1 = "one";
String s2 = "two";
String[] arr3 = {s1, s2, "three"};
int[] arr4 = {10, 20, 17};

arr3 = new String[] {"four", "five"};  // array declared earlier
arr4 = new int[] {31, 47};             // array declared earlier

Accessing Elements of an Array

We can get the value stored at a particular index in the array using brackets and the index.

String first = arr3[0];
int last = arr4[1];

Arrays are implemented as objects on the heap and have a length property that can be used to get the size of the array. Note that length is not a method, but rather a property.  We can access properties (a.k.a. fields) using the dot operator as we did with methods, however we omit the parenthesis.

System.out.println("Size: " + arr4.length);   // prints 2

We can access all of the elements in an array using a for-loop to iterate over all of the possible array indices.  In the example below, we initialize all of the elements in the array to 1.

for (int i = 0; i < arr4.length; i++) {
    arr4[i] = 1;
}

For-each Loops

For-each loops allow us to iterate through all of the elements in the array without having to use indices.  For-loops can not be used to modify an array( add element, remove element, change element), but are useful when you need to process each element.

for (int element : arr4) {
    System.out.printf("%d ", element);
}

Arrays are Reference Types

  • Stored on the heap
  • We can pass references to arrays into functions
  • Arrays passed into a function can be modified within the function
  • We can return reference to arrays.
  • Memory is reserved so long as it is referenced by some variable.

Passing and Returning Arrays

public static void main(String[] args) {
    int[] ages = initArray(10);
    System.out.println("Total ages: " + sum(ages));
}

static int[] initArray(int size) {
    int[] arr = new int[size];

    for (int i = 0; i < arr.length; i++) { 
        arr[i] = i; 
    }

    return arr;
}

static int sum(int[] arr) {
    if (arr == null) {
        return 0; 
    }
    int sum = 0;
    for (int elm : arr) {
        sum += elm;
    }
    return sum;
}

Notice that we check to see if arr is null in the sum function.  Before ever calling a method or accessing a field on a reference type variable, make sure it is not null (or use a try-catch statement).

© 2017 – 2020, Eric. All rights reserved.