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.

AP Computer Science A illustration with code, binary digits, and programming braces
Inside this lesson 9 sections 5 questions 9 figures

SECTION 1

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?

SECTION 2

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.

SECTION 3

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.

Array Reference and Heap ObjectStack (variable)int[] scoresreferenceHeap — Array Object (length = 5)9085729864[0][1][2][3][4]Three Ways to Create an Array1. Declare + Allocateint[] a;a = new int[5];2. Single Statementint[] a = new int[5];3. Initializer Listint[] a = {90,85,72,98,64};⚠ Common Pitfall: Off-by-One Errorscores[5] → ArrayIndexOutOfBoundsExceptionValid indices for length 5: 0, 1, 2, 3, 4
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.

SECTION 4

How Array Creation & Access Work

Declaration Syntax

DECLARATION

type[]variableName;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=newtype[size];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=val0,val1,...,valn−1;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]//readorwritevariableName[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

SECTION 5

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.

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];

Java array default initialization values by element type

Traversal Patterns: Standard for vs. Enhanced for-eachStandard for Loopfor (int i = 0;i < arr.length; i++){// arr[i] = read/write}✔ Can read and modify elements✔ Access to the index variable✔ Can traverse in reverse⚠ Off-by-one risk with boundsUse when you need the indexor need to modify elements.Enhanced for-each Loopfor (int val : arr){// val = read-only copy}✔ Cleaner syntax, no index needed✔ No risk of off-by-one errors✔ Works for any iterable⚠ Cannot modify array elementsUse when you only need toread each element sequentially.
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.

SECTION 6

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.

Worked example

  1. 1

    Step 1 — Declare and initialize the array

    Use 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. 2

    Step 2 — Accumulate the sum using a for loop

    Declare 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. 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. 4

    Step 4 — Print the result

    System.out.println("Average: " + avg); prints Average: 81.8 to the console.
    Output: Average: 81.8
ℹ
Integer Division Trap

SECTION 7

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.

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 differences between arrays and ArrayLists on the AP CS A exam

SECTION 8

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.

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

Extending 1D array concepts to 2D arrays

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.

SECTION 9

Practice Problems

Question 1: CONCEPTUAL

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
  • A. 2
  • B. 0
  • C. null
  • D. An ArrayIndexOutOfBoundsException is thrown
Show answer (B)
B. 0 When an int[] is created with new, every element is initialized to 0. Index 2 is valid (valid indices are 0–3 for length 4), so the output is 0. A is wrong because Java does not store the index value in the element. C is wrong because null is the default for reference types, not primitives. D is wrong because index 2 is within bounds.

Question 2: BASIC CALCULATION

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
  • A. red
  • B. green
  • C. blue
  • D. An ArrayIndexOutOfBoundsException is thrown
Show answer (C)
C. blue The array has length 3, so colors.length - 1 evaluates to 2. colors[2] is "blue", the last element. A is wrong because "red" is at index 0. B is wrong because "green" is at index 1. D is wrong because length - 1 is always a valid index for a non-empty array.

Question 3: INTERMEDIATE

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
  • A. 20
  • B. 23
  • C. 24
  • D. 25
Show answer (B)
B. 23 The loop modifies each element by adding its index to its current value. At k = 3: arr[3] = 20 + 3 = 23. Since the loop runs from the last index backward, index 4 is processed first (25 + 4 = 29), then index 3 (20 + 3 = 23). The value at index 3 does not depend on later iterations. A is wrong because it ignores the modification. C is wrong because it adds 4 (the wrong index) to 20. D is wrong because it adds 5 to 20, confusing length with index.

Question 4: APPLIED

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}.
Show answer
Sample solution: public static void replaceNegatives(int[] arr) { for (int i = 0; i < arr.length; i++) { if (arr[i] < 0) { arr[i] = 0; } } } Rubric: • (1 pt) Correct method header: public static void, correct parameter type int[]. • (1 pt) Correct loop traversing all valid indices (0 to arr.length − 1). • (1 pt) Correct conditional check arr[i] < 0. • (1 pt) Correctly assigns arr[i] = 0 inside the conditional. Note: An enhanced for-each loop would NOT work here because assigning to the loop variable does not modify the array element.

Question 5: CRITICAL 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}.
Show answer
Sample solution: int[] reversed = new int[original.length]; for (int i = 0; i < original.length; i++) { reversed[i] = original[original.length - 1 - i]; } Rubric: • (1 pt) Creates a new array with the same length as original. • (1 pt) Correct loop bounds covering all indices. • (1 pt) Correct index mapping: reversed[i] gets original[original.length − 1 − i]. The key insight is the index transformation: position i in the reversed array maps to position (length − 1 − i) in the original. This avoids modifying the original array since all reads come from original and all writes go to reversed.

Varsity Tutors • AP Computer Science A • Array Creation and Access