Fiveable
Fiveable
AP Computer Science A

💻ap computer science a review

6.1 Array Creation and Access

Verified for the 2025 AP Computer Science A examLast Updated on June 18, 2024

Arrays help programmers organize lots of related data without creating separate variables for each piece of information. Think of arrays like a row of labeled boxes where you can store similar items together—making your code cleaner and easier to work with.

What is an Array?

An array is like a collection of numbered storage containers that all hold the same type of item. Imagine a row of identical lockers, each with its own number (starting at 0), and each storing one item of the same type.

Key Characteristics

  • Fixed Size: Once you create an array, you can't change how many containers it has.
  • Ordered Collection: Items are stored in a specific sequence with numbered positions.
  • Same Type Only: All items must be of the same type (like all numbers or all text).
  • Starts at Zero: The first item is at position 0, not 1 (this trips up many beginners!).

Creating Arrays in Java

Here are the main ways to make arrays:

1. Two-Step Creation: Declare First, Then Create

// First, say you want an array of numbers
int[] numbers;

// Then, create an array with 5 empty spots
numbers = new int[5];

2. One-Step Creation

// Create and set up an array with 10 spots in one step
int[] scores = new int[10];

3. Creating with Initial Values

// Create an array already filled with specific values
String[] days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"};

Default Values

When you create a new array using new, Java automatically fills it with "starter" values:

Data TypeDefault ValueWhat It Means
int0Zero
double0.0Zero
booleanfalseNot true
Objects (like String)nullEmpty - no object
int[] nums = new int[3];
// nums contains: [0, 0, 0]

double[] measurements = new double[2];
// measurements contains: [0.0, 0.0]

boolean[] flags = new boolean[2];
// flags contains: [false, false]

String[] names = new String[2];
// names contains: [null, null] (null means "nothing here yet")

Accessing Array Elements

To get or change items in your array, use square brackets [] with the position number:

// Create an array with 5 spots
int[] values = new int[5];

// Put values into specific positions
values[0] = 10;  // First position (remember, we start at 0!)
values[1] = 20;  // Second position
values[4] = 50;  // Last position

// Get values from positions
System.out.println(values[2]);  // Prints 0 (the default value)

Array Positions (Indices)

  • Valid positions go from 0 to (array length - 1)

  • If you try to access a position that doesn't exist, you'll get an error called ArrayIndexOutOfBoundsException - this is Java's way of telling you that you're trying to use a position number that's outside the valid range of the array

int[] data = new int[3];  // Creates array with positions 0, 1, and 2

// These work fine
data[0] = 100;
data[2] = 300;

// These will crash your program
// data[-1] = 50;  // There's no negative position
// data[3] = 400;  // Position 3 doesn't exist in a 3-item array

Common Array Operations

Finding Out How Big an Array Is

Use the length property to see how many spots are in an array:

int[] scores = new int[25];
System.out.println(scores.length);  // Prints: 25

Going Through All Items in an Array

// Using a regular for loop with position numbers
int[] numbers = {10, 20, 30, 40, 50};
for (int i = 0; i < numbers.length; i++) {
    System.out.println("Item at position " + i + ": " + numbers[i]);
}

// Using enhanced for loop (easier but doesn't give you the position)
for (int num : numbers) {
    System.out.println("Value: " + num);
}

Visualizing an Array

Let's see what happens with this code:

int[] values = new int[4];
values[0] = 10;
values[1] = 20;
values[3] = 40;

Here's what the array looks like in memory:

Position0123
Value1020040

Notice position 2 still has the default value (0) because we never put anything there!

Common Array Mistakes

  1. Forgetting arrays start at 0: The first position is 0, not 1

    int[] nums = new int[5];  // Valid positions: 0,1,2,3,4
    
  2. Trying to access positions that don't exist (causes ArrayIndexOutOfBoundsException):

    int[] values = new int[3];
    values[3] = 10;  // Error! Valid positions are only 0,1,2
    
  3. Using an array you created but never initialized:

    int[] data;         // Said we want an array, but didn't create it
    data[0] = 5;        // Error! The array doesn't actually exist yet
    

Summary

Arrays let you store many related values together using a single variable name. We've learned how to create arrays, put values in them, and get values out using position numbers (indices). Remember that arrays have a fixed size that can't change, positions start counting at 0, and you'll get errors if you try to access positions outside the array's valid range.

Key Terms to Review (7)

ArrayIndexOutOfBoundsException: ArrayIndexOutOfBoundsException is an exception that occurs when trying to access an invalid index position in an array. It is thrown to indicate that the index used to access an array is either negative or greater than or equal to the size of the array.
ArrayName.length: The property "length" is used to determine the number of elements in an array.
Arrays: Arrays are a collection of elements of the same data type, stored in contiguous memory locations. They have a fixed size and can be accessed using an index.
Fixed size: Fixed size refers to a data structure or container whose size cannot be changed once it is created. Once initialized with a specific capacity or length, no additional elements can be added or removed from it.
Import java.util.Arrays;: This term refers to a statement in Java that allows you to access the functionality of the Arrays class from the java.util package. It is used to import specific classes or entire packages into your program.
Primitive data type: Primitive data types are basic data types provided by programming languages, such as integers, floating-point numbers, booleans, and characters. They represent simple values and have predefined characteristics.
Reference Data Type: A reference data type is a data type that refers to an object in memory rather than directly storing the value. It stores the memory address where the object is located.