Arrays Overview

  • Arrays are 10-15% of the AP CSA Exam
  • The four main topics that College Board wants you to know
    • Array creation and access
    • Traversing arrays
    • Enhanced for loops for arrays
    • Developing algorithms using arrays
  • The overall purpose of arrays is to store multiple values in a single variable, instead of declaring separate variables for each value.

6.1 Array Creation and Access

  • Arrays are used to store one data type
  • Unlike Arraylists, arrays have a fixed size and cannot be changed
  • Arrays can be denoted using braces {} Below is an example of a simple array storing our scrum team names
    [Meena, Shraddha, Madhumita, Pranavi]
  • To use an array you have to use the command
    import java.util.Arrays;

Making Arrays

There are two ways to make arrays

  • using constructors
  • using pre-intiliazed arrays
dataType[] arrayName = new dataType[numberOfItems]; //Constructor
int[] arraySample = {1,3,5,7,9}; //pre-initialized arrays

Accessing Elements in Arrays

  • You can access the elements in an array using different commands
arrayName.Length //determine the size
arrayName.length - 1 //to access the last item in the array

6.2 Traversing Arrays

  • Traversing is accessing every value in the array
  • Can be done using a loop like a for loop or while loop
  • Below is an example - using a for loop, we can iterate through each fruit in the array of Strings and print it out
// Here is the array we will be working with
String[] myFruits = new String[] {"Apple", "Strawberry", "Watermelon", "Blueberry"};

for (int i = 0; i < myFruits.length; i++) {
    System.out.println("Fruit number " + i + " is " + myFruits[i]);
}
  • Can also loop through an array in reverse
for (int i = myFruits.length - 1; i >= 0 ; i--) {
    System.out.println("Fruit number " + i + " is " + myFruits[i]);
}
  • If we have a list of numbers, we could change each value in the array by a certain amount
// Here is the array we will be working with
int[] myNumbers = new int[] {1, 3, 5, 7, 9};

for (int i = 0; i < myNumbers.length; i++) {
    // add 10 to each element in the array
    myNumbers[i] += 10;
    System.out.println("New element " + i + " is " + myNumbers[i]);
}
  • We can also traverse an array using a while loop
// Here is the array we will be working with
String[] myFruits = new String[] {"Apple", "Strawberry", "Watermelon", "Blueberry"};

int i = 0; 
while (i < myFruits.length) {
    System.out.println("Fruit number " + i + " is " + myFruits[i]);
    i++;
}

Bound Errors

  • ArrayIndexOutOfBoundsException thrown, can happen when using loops to access array elements
  • In the example below instead of the condition being while the index is less than the length of the array, the condition is less than or equal too
  • This mean the loop will try to run when i = 4 (since the length of the list is 4). However since array index starts from 0, the last item in the array will have an index of 3. So, index of 4 will be out of bounds, resulting in the error.
int i = 0; 

while (i <= myFruits.length) {
    System.out.println("Fruit number " + i + " is " + myFruits[i]);
    i++;
}

6.3 Enhanced for loop for Arrays

This topic was pretty short, but essentially what you need to know is about the enhanced for loop. The enhanced for loop can be used to traverse through most data structures (i.g. arrays). However, it can only traverse in a forward direction. Usually the structure is like so

for (dataType i: arrayName) {
  do something with i
}

Essentially, this code mentions how every element in the array (i) has to have something done to it. It's important to note that although there is access to the element i, but it isn't possible to change the value/set new values to element i.

We can use mutator methods on objects on the array to set the value of their instance variables. This is because i is a copy of the object reference, which means that i refers to the same object as the array element, so calling methods on i is the same as calling methods on the individual array elements themselves. For example

public class Student {
    private String name;
    
    /** Sets the name of the Student
    */
    public void setName(String name) {
      this.name = name;
    }
  
    /** Other instance variables, methods, and constructors not shown
    */
  }
  // IN ANOTHER CLASS
  /** Resets all students' names
  */
  public static void doubleArray(Student[] array, String defaultName) {
    for (Student student: array) {
      student.setName(defaultName); // Sets each student's name to a default name
    }
  }

6.4 Developing Algorithms using Arrays

Here are some algorithms that arrays can be used for (from college board standards),

  • Minimum and Maximum of a list of elements
  • Compute the sum, average, or mode of multiple elements
  • Determine if at least one element has a property
  • Access consecutive pairs of elements
  • Determine duplicates

What to use when problem solving with arrays .length can be used to find the length of an array

  • The value at a specific index can be found with array[i], where i is the index
  • An element at index i can be replaced using array[i] = new element
  • You can iterate over an array with a for loop
    for(type element: array) {
      \\\\ code here

Computing Sums with Arrays

See the code below for a sample algorithm of how to compute the sum of elements in an array. This could be applied to finding the mean, standard deviation, or any other algorithm that requires summation.

int[] array = {5, 1, 78}; // intialize

int sum  = 0; // variable to keep track of sum

for (int number : array) { // iterates over each loop in the array
    sum += number; // the number is added to the sum
}

System.out.println(sum); //expected sum is 84, so 84 should be printed
84