Array Creation and Access

The Parking Garage

Before any code, picture a small parking garage under construction. The contractor is told to build exactly 5 spots — no more, no less. Once the concrete is poured, spot 5 doesn’t exist and never will unless the whole garage gets torn down and rebuilt bigger. That upfront, locked-in decision is exactly what happens every time an array gets declared in Java.

Keep that garage in mind for the rest of this lesson — every idea below maps back to it.

  • An array is a data structure that reserves a fixed block of memory to hold a collection of values of the same type — the garage itself.
  • An element is a single value stored in the array — a car in a spot.
  • The index of an element is its position in the array — the spot number painted on the ground.
    • In Java, the first element sits at index 0 — spot numbering starts at the entrance, not at “1.”
  • The length of an array is how many elements it can hold — how many spots the contractor poured.
    • length is a public final data member of every array.
      • public means any class can check it — no getter method needed.
      • final means it’s locked in at construction — you cannot resize an array after it’s built.
    • The last valid index of an array named list is always list.length - 1 — the last spot is one before the total count, because counting starts at 0.

A Look Into Array Memory

The next line only pours the concrete — it doesn’t park anything. Watch how the array’s contents look before a single value has been set.

int[] listOne = new int[5];

This doesn’t put any cars in the garage — it just pours the concrete. Java reserves space for 5 integers and fills every spot with a default value, because “empty” isn’t a real value a computer can store — it has to put something there.

ARRAY: [0, 0, 0, 0, 0]
INDEX:  0  1  2  3  4

The default depends entirely on what type of “car” the garage was built for:

Data Type Default Value
byte (byte) 0
short (short) 0
int 0
double 0.0
boolean false
char '\u0000'

Parking a car (inserting a value):

listOne[0] = 5;
ARRAY: [5, 0, 0, 0, 0]
INDEX:  0  1  2  3  4

Building the garage pre-loaded (an initializer list):

int[] listTwo = {1, 2, 3, 4, 5};
ARRAY: [1, 2, 3, 4, 5]
INDEX:  0  1  2  3  4

Asking for a spot that doesn’t exist: If code reaches for an index outside the array’s range, Java throws an ArrayIndexOutOfBoundsException. This isn’t Java being difficult — it’s Java refusing to read memory that was never reserved. Asking for listOne[5] in a 5-spot garage is like radioing the attendant and asking them to pull a car off a level of the garage that was never built.

Printing the garage, not the cars: System.out.println(listOne) does not print the contents. It prints the array’s memory reference (something like [I@28a6ceb) — the equivalent of shouting out the garage’s street address instead of listing what’s parked inside. To actually see what’s stored, you have to walk the garage and check each spot yourself.

The block below ties all three ideas together in one place — creating the garage, parking cars at specific spots, deliberately tripping the out-of-bounds error, and comparing what printing the array reference looks like versus printing an actual value:

/* creating and modifying the garage */
int[] listOne = new int[5];        // ARRAY: [0, 0, 0, 0, 0]

listOne[2] = 33;                    // ARRAY: [0, 0, 33, 0, 0]
listOne[3] = listOne[2] + 3;        // ARRAY: [0, 0, 33, 36, 0]

try {
    listOne[5] = 13;                // no such spot — this will throw
} catch (Exception e) {
    System.out.println("Error at listOne[5] = 13");
    System.out.println("ArrayIndexOutOfBoundsException: that spot was never built!");
}

System.out.println(listOne);        // prints the garage's address, not its contents
System.out.println(listOne[4]);     // this actually checks spot 4 and prints its value

Popcorn Hack 1

You’re the new garage attendant on your first shift. Walk the whole garage and call out the ticket number posted at every single spot in listOne, one line at a time.

Click to reveal an example solution
for (int i = 0; i < listOne.length; i++) {
    System.out.println("Spot " + i + ": " + listOne[i]);
}

Parking More Than Just Cars: Arrays of Objects

Garages don’t only hold identical sedans — this one can hold buses, motorcycles, whatever type it was built for. Arrays work the same way: they can hold objects, not just primitives. Say there’s a Student class already built, and the goal is an array holding every student in the class.

Student[] classList;
classList = new Student[3];

Here’s the part that trips people up: pouring the concrete for an object array does not create any objects. Every spot starts out empty — null by default — because Java has no idea what a “default student” would even look like. The spots have to be filled by hand:

classList[0] = new Student("Bob", 12, 3.5);
classList[1] = new Student("John", 11, 4.0);
classList[2] = new Student("Steve", 10, 3.75);

Try to read classList[1].getName() before that line runs, and it throws a NullPointerException — there’s no car in that spot yet, so there’s nothing to ask for.

Popcorn Hack 2

Grab a class you’ve already built this year. Create an array of objects from it, then walk the array and print out each object using:

  1. a for loop
  2. a while loop

<detail markdown=”1”s>

Click to reveal an example solution
Student[] classList = new Student[3];
classList[0] = new Student("Bob", 12, 3.5);
classList[1] = new Student("John", 11, 4.0);
classList[2] = new Student("Steve", 10, 3.75);

// using a for loop
for (int i = 0; i < classList.length; i++) {
    System.out.println(classList[i]);
}

// using a while loop
int i = 0;
while (i < classList.length) {
    System.out.println(classList[i]);
    i++;
}

</details>

The Walkthrough: Enhanced For Loops

A standard indexed loop hands you the spot number and the car. An enhanced for loop (also called a for-each loop) only hands you the car — it walks the garage row by row and shows you what’s parked, without ever telling you which spot it came from.

The signature has two parts separated by a colon instead of three separated by semicolons:

for (type variableName : arrayName) {
    // statement one;
    // statement two;
    // ...
}

Two catches worth remembering:

  • There’s no access to the index or bracket notation inside the loop — you only ever see the value.
  • The loop variable is a copy of each value. Reassigning it inside the loop does nothing to the actual array — it’s like scribbling a new label on your own clipboard without repainting the number on the ground.

Popcorn Hack 3

Build an array, then use an enhanced for loop to print out every element.

Click to reveal an example solution
int[] ticketNumbers = {102, 118, 97, 145, 103};

for (int ticket : ticketNumbers) {
    System.out.println(ticket);
}

Finding the Longest-Parked Car: Min/Maxing

Every car that pulls into this garage takes a ticket with a sequential number stamped on it. To find whoever has been parked the longest, the goal is finding the smallest ticket number across every occupied spot — the same core technique used to find the max or min value anywhere in an array.

The pattern:

  1. Grab a local variable to track the current best answer.
  2. Start it at either the first element or the mathematical opposite extreme (a very large number when hunting for a min, a very small one when hunting for a max).
  3. Walk every element — with a standard loop or an enhanced one — and compare it against the current best. Replace the current best whenever a better one shows up.
  4. When the loop ends, that variable holds the answer and is still in scope to return.

This method turns that four-step pattern into code — notice lowest is the “current best” variable, seeded with the first ticket before the loop even starts:

public static int earliestTicket(int[] ticketNumbers) {
    int lowest = ticketNumbers[0];   // start by assuming the first car is the winner

    for (int i = 1; i < ticketNumbers.length; i++) {
        if (ticketNumbers[i] < lowest) {
            lowest = ticketNumbers[i];
        }
    }

    return lowest;
}

Popcorn Hack 4

Create two arrays — one of int, one of double. Use both a standard for loop and an enhanced for loop to find the max and min of each array.

Click to reveal an example solution
int[] ticketNumbers = {102, 118, 97, 145, 103};
double[] parkingFees = {4.50, 12.25, 3.75, 9.00, 6.50};

// standard for loop
int lowestTicket = ticketNumbers[0];
for (int i = 1; i < ticketNumbers.length; i++) {
    if (ticketNumbers[i] < lowestTicket) {
        lowestTicket = ticketNumbers[i];
    }
}

// enhanced for loop
double highestFee = parkingFees[0];
for (double fee : parkingFees) {
    if (fee > highestFee) {
        highestFee = fee;
    }
}

System.out.println("Earliest ticket: " + lowestTicket);
System.out.println("Highest fee: " + highestFee);

⚠️ Watch Out

A few mistakes that show up constantly when this topic first gets introduced:

  • Printing an array directly (System.out.println(arr)) prints a memory reference, not the values. It compiles fine and still won’t give the answer you’re looking for.
  • Off-by-one errors — using <= instead of < in a loop condition against .length reaches one spot past the last valid index and throws ArrayIndexOutOfBoundsException.
  • Assuming object arrays come pre-built — new Student[3] reserves 3 empty spots, not 3 students. Touching a spot before assigning it throws NullPointerException.
  • Trying to modify the array through an enhanced for loop — the loop variable is a copy. Use a standard indexed loop when the goal is to actually change values in place.

References

College Board. (2025). AP Computer Science A course and exam description [Effective fall 2025]. Unit 4: Data Collections, Topic 4.3 Array Creation and Access (p. 109). https://apcentral.collegeboard.org/media/pdf/ap-computer-science-a-course-and-exam-description-effective-fall-2025.pdf