AP COMPUTER SCIENCE A • DATA COLLECTIONS

Array Creation and Access

Master the fixed-size, indexed data structure at the heart of Java programming and the AP exam.

Historical Context & Motivation

Long before high-level languages existed, programmers needed a way to store collections of related data—test scores for an entire class, pixel values across an image, or sensor readings over time. Storing each datum in its own named variable quickly becomes unmanageable: imagine declaring score0 through score999. The array was invented to solve exactly this problem: it groups multiple values of the same type under a single name and accesses each one by its numerical index.

1950s
FORTRAN Introduces Arrays
IBM's FORTRAN language introduced subscripted variables, allowing programmers to use a single name with an integer index to reference a collection of values stored in contiguous memory.
1972
C Formalizes Zero-Indexed Arrays
Dennis Ritchie's C language tied arrays directly to pointer arithmetic, establishing zero-based indexing as a convention that would influence nearly every subsequent language.
1995
Java Adopts Safe, Object-Based Arrays
Java inherited zero-based indexing from C but added automatic bounds checking, throwing an ArrayIndexOutOfBoundsException instead of silently corrupting memory.
2003–Present
AP CS A Curriculum Centers on Arrays
The College Board's AP Computer Science A course identifies arrays (and ArrayLists) as foundational data structures, testing creation, traversal, and algorithmic manipulation every year.

Understanding arrays is not merely an academic exercise. Every sorting algorithm, every search routine, and every matrix operation you will encounter on the AP exam presupposes fluency with array creation, element access, and bounds management. The central question this lesson addresses is: How do we declare, instantiate, and safely access elements in a Java array?

Core Principles & Definitions

A Java array is a fixed-length, ordered collection of elements that share a single data type. Once created, its length cannot change—this immutability of size distinguishes arrays from resizable structures like ArrayList. Four foundational principles govern how arrays behave in Java, and mastering them is essential before tackling traversal algorithms or free-response problems on the AP exam.

1

Fixed Size at Creation

The size of an array is determined when you use new and cannot be changed afterward. To "grow" an array you must create a new, larger one and copy the elements over.
2

Zero-Based Indexing

The first element lives at index 0 and the last at index length − 1. Attempting to use index length causes an ArrayIndexOutOfBoundsException.
3

Default Initialization

When you allocate an array with new, Java fills every slot with a default value: 0 for numeric types, false for booleans, and null for reference types.
4

Homogeneous Type

All elements must be the declared type (or a compatible subtype). A double[] cannot hold a String; a Shape[] can hold any object whose class extends Shape.
KEY TAKEAWAY
KEY TAKEAWAY

Visual Explanation — Array Memory Layout

The following diagram illustrates the relationship between a reference variable, the array object on the heap, and individual indexed elements. Understanding this picture is critical because many exam questions test whether students recognize that the variable itself holds a reference to the array, not the array data itself.

The variable scores on the stack stores a reference (arrow) to the array object on the heap. Each cell is accessed by its zero-based index shown in brackets below. The three creation idioms and the common off-by-one pitfall are summarized at the bottom.

Notice that the reference variable on the stack is separate from the array data on the heap. If you assign one array variable to another—int[] copy = scores;—both variables point to the same object. Modifying an element through one reference changes what the other sees. This aliasing behavior is a frequent source of exam questions.

How Array Creation & Access Work

Declaration Syntax

DECLARATION
type[] variableName;
type is any primitive or reference type. The brackets indicate an array. No memory is allocated yet; the variable is null until instantiation.

Instantiation with new

INSTANTIATION
variableName = new type[size];
size must be a non-negative integer (it can be 0). Java allocates size contiguous slots, each initialized to the type's default value.

Initializer List (Combined)

INITIALIZER LIST
type[] variableName = {val₀, val₁, ..., valₙ₋₁};
The compiler infers the length from the number of values listed. This syntax is only valid in a declaration statement; you cannot use it in a standalone assignment after declaration.

Element Access & Mutation

ACCESS / MUTATE
variableName[index] // read or write
Valid indices range from 0 to variableName.length − 1. The expression variableName.length (no parentheses—it is a field, not a method) returns the array's size.
AP Exam Tip

Default Values & Common Patterns

When Java allocates an array with new, it zero-fills the memory. The actual default value depends on the element type. Understanding these defaults prevents subtle bugs—for example, summing an uninitialized int[] yields 0, while calling a method on an element of an uninitialized String[] throws a NullPointerException.

Java array default initialization values by element type
Element TypeDefault ValueExample Declaration
int0int[] nums = new int[3];
double0.0double[] gpa = new double[5];
booleanfalseboolean[] flags = new boolean[4];
Any reference type (String, Object, etc.)nullString[] names = new String[10];
Side-by-side comparison of the two traversal patterns tested on the AP exam. The standard for loop gives full control via the index, while the enhanced for-each loop provides a read-only copy of each element.

A critical distinction for the AP exam: in an enhanced for-each loop over a primitive array, the loop variable val is a copy of the element. Assigning a new value to val does not change the array. However, for an array of objects, val is a copy of the reference—so calling a mutator method on val does modify the underlying object.

Worked Example — Computing an Average

Consider the following task: given an array of quiz scores, compute and print the class average. This exercise combines array creation, traversal, and access—the three skills most frequently tested on the AP exam.

1
Step 1 — Declare and initialize the arrayUse an initializer list to create the array with known values: int[] scores = {90, 85, 72, 98, 64};. The compiler determines the length to be 5.
scores.length → 5
2
Step 2 — Accumulate the sum using a for loopDeclare an accumulator int sum = 0; and iterate: for (int i = 0; i < scores.length; i++) { sum += scores[i]; }. After the loop: sum = 90 + 85 + 72 + 98 + 64.
sum → 409
3
Step 3 — Compute the average (watch for integer division)Compute double avg = (double) sum / scores.length;. The cast to double is essential—without it, Java performs integer division and truncates the decimal, yielding 81 instead of 81.8.
avg → 81.8
4
Step 4 — Print the resultSystem.out.println("Average: " + avg); prints Average: 81.8 to the console.
Output: Average: 81.8
Integer Division Trap

Arrays vs. ArrayLists — Strengths & Limitations

The AP CS A curriculum explicitly pairs arrays with ArrayList and expects students to choose the right tool for a given scenario. An array is faster and leaner when the number of elements is known in advance, while an ArrayList provides dynamic resizing at the cost of additional overhead.

Key differences between arrays and ArrayLists on the AP CS A exam
FeatureArrayArrayList
SizeFixed at creationGrows/shrinks dynamically
PrimitivesStores primitives directlyRequires wrapper classes (Integer, Double)
Access syntaxarr[i]list.get(i)
Mutation syntaxarr[i] = val;list.set(i, val);
Length / Size.length (field).size() (method)
Bounds checkingArrayIndexOutOfBoundsExceptionIndexOutOfBoundsException
Insert / RemoveMust shift elements manuallyBuilt-in add/remove methods
KEY TAKEAWAY
KEY TAKEAWAY

Connection to 2D Arrays & Advanced Topics

A one-dimensional array is the building block for more complex structures. In AP CS A, 2D arrays (arrays of arrays) are tested in their own unit. Conceptually, a 2D array is simply a 1D array whose elements are themselves 1D arrays. Mastering single-dimensional creation and access makes the leap to int[][] grid = new int[rows][cols]; a natural extension.

Extending 1D array concepts to 2D arrays
Concept1D Array2D Array
Declarationint[] a;int[][] a;
Instantiationnew int[n]new int[r][c]
Accessa[i]a[r][c]
Row countN/Aa.length
Column countN/Aa[0].length
TraversalSingle for loopNested for loops

Beyond the AP exam, arrays underpin virtually every major data structure and algorithm. Hash tables use arrays for their buckets, heaps are stored as arrays with implicit tree structure, and dynamic programming solutions often fill arrays bottom-up. The skills you build now—careful index management, bounds checking, and traversal pattern selection—translate directly to these more advanced topics in a data structures and algorithms course.

Practice Problems

1
Consider the following code segment: int[] data = new int[4]; System.out.println(data[2]); What is printed? A. 2 B. 0 C. null D. An ArrayIndexOutOfBoundsException is thrown
2
What is the output of the following code? String[] colors = {"red", "green", "blue"}; System.out.println(colors[colors.length - 1]); A. red B. green C. blue D. An ArrayIndexOutOfBoundsException is thrown
3
Consider the following code segment: int[] arr = {5, 10, 15, 20, 25}; for (int k = arr.length - 1; k >= 0; k--) { arr[k] = arr[k] + k; } System.out.println(arr[3]); What is printed? A. 20 B. 23 C. 24 D. 25
PROBLEM 4APPLIED
Write a static method replaceNegatives that takes an int[] parameter and replaces every negative element with 0. The method returns nothing (void). For example, if arr is {3, -1, 5, -7, 2}, after calling replaceNegatives(arr), the array becomes {3, 0, 5, 0, 2}.
PROBLEM 5CRITICAL THINKING
Write a code segment that, given an int[] original, creates a new array reversed containing the same elements in reverse order. The original array must not be modified. For example, if original is {1, 2, 3, 4}, then reversed should be {4, 3, 2, 1}.
Varsity Tutors • AP Computer Science A • Array Creation and Access