APCS Java Dojo  •  Kata #1 of 7+
Motel icon TechNoviceTools — APCS Java Dojo
Kata #1

Primitive Arrays &
the Arrays Class Toolkit

No frills. Fixed rooms. Numbered starting from zero.
It’s the Java Motel — a bit old-school, completely dependable,
and the foundation everything else is built on.

What you will drill

Kata #1 — Primitive Arrays

This kata covers everything the AP exam expects you to know cold about primitive arrays: how they are declared, how String[] args connects them to real programs, how to traverse them reliably, the most common algorithmic patterns, a critical gotcha with println(), and the Arrays class methods that unlock their true power. After this kata, you will reach for .length (not .length()), use Arrays.toString() without thinking, and know exactly when to use the indexed for loop vs. the enhanced for — automatically.

— or jump to a section:

AP EXAM FAST FACTS

  • Primitive arrays appear in every APCS-A free-response set
  • arr.length — a field, not a method (no parens!)
  • Arrays are zero-indexed: first element is arr[0]
  • Default values: int[] → 0, boolean[] → false, String[] → null
  • Arrays.sort() sorts in place — void return
  • Arrays.binarySearch() requires a sorted array first
  • Import: import java.util.Arrays;

Imagine a roadside motel from the 1960s or 70s — the kind you see driving through the desert. Single story. Numbered doors in a straight line. No elevator, no room service, no amenities beyond four walls and a key. You pull up, the manager assigns you a room number, and that’s where you live for the night. That’s a Java primitive array.

🏨 The Java Motel Rules:
  • Rooms are numbered starting from 0, not 1. Room 0, Room 1, Room 2… (Computers count from zero!)
  • The number of rooms is fixed when the motel is built. You cannot add or remove rooms after construction.
  • Each room holds exactly one item of one specific type (all rooms are int, or all rooms are String, etc.)
  • To find someone, you must know their room number. There is no concierge and no search function built in.
  • The motel knows how many rooms it has: motelName.length — that’s it. No other built-in features.

The Three Stooges check in:

// A three-room motel for the Stooges
String[] stooges = {"Moe", "Larry", "Curly"};

// Visual layout of the motel:
//  ┌──────────┬──────────┬──────────┐
//  │  Room 0  │  Room 1  │  Room 2  │
//  │  "Moe"   │ "Larry"  │ "Curly"  │
//  └──────────┴──────────┴──────────┘
//     stooges[0]  stooges[1]  stooges[2]
//     stooges.length = 3

System.out.println(stooges[0]);  // Moe   — who's in Room 0?
System.out.println(stooges[2]);  // Curly — who's in Room 2?
System.out.println(stooges.length); // 3    — how many rooms?
Gotcha — The Off-By-One Trap

The last valid room in a 3-room motel is Room 2 (not Room 3). stooges[3] throws an ArrayIndexOutOfBoundsException. The pattern is always: valid indices are 0 through arr.length - 1.

stooges[stooges.length] is ALWAYS out of bounds. Exam questions are built around this.

Way 1 — Initializer List (small motels, all rooms known upfront)

Use when you know all values at declaration time. The compiler counts the rooms for you.

String[] stooges = {"Moe", "Larry", "Curly"};  // 3 rooms
char[] vowels    = {'a', 'e', 'i', 'o', 'u'}; // 5 rooms
int[]  primes    = {2, 3, 5, 7, 11, 13};        // 6 rooms

// [] brackets may follow the type OR the variable name — both are valid:
// String[] stooges = ...  ← preferred style
// String stooges[] = ...  ← also valid (C-style legacy)

Way 2 — With new (rooms empty, fill in later)

Use when you know the size but not yet the values. All rooms get default values (0, false, null).

int[] scores = new int[5]; // 5 rooms, all initialized to 0
// ┌───┬───┬───┬───┬───┐
// │ 0 │ 0 │ 0 │ 0 │ 0 │   ← default int value = 0
// └───┴───┴───┴───┴───┘

scores[0] = 95;  // check a value into Room 0
scores[1] = 87;  // check a value into Room 1
scores[2] = 72;  // etc.

String[] names = new String[3]; // 3 rooms, all null — be careful!

Way 3 — From a delimited String (using split())

String avengers = "Thor|Iron Man|Captain America|Hulk|Black Widow";
String[] team = avengers.split("|");
// team[0] = "Thor", team[1] = "Iron Man", etc.
Remember: Once a motel is built with new int[5], it has exactly 5 rooms forever. You cannot call a contractor to add rooms. If you need a bigger motel, you must build a new one (or switch to an ArrayList — see Kata #2).

Every Java program has a main method with this exact signature: public static void main(String[] args). That String[] args is a primitive array that Java fills with any command-line arguments you pass when running the program. It is the first array every Java programmer encounters — and it is usually explained as boilerplate and ignored. It shouldn’t be.

🚗 Pulling into the motel: When you run
java ThreeStoogesDriver Moe Larry Curly
Java builds a 3-room motel and hands it to main as args:
// ┌──────────┬──────────┬──────────┐
// │  args[0] │  args[1] │  args[2] │
// │  "Moe"   │ "Larry"  │ "Curly"  │
// └──────────┴──────────┴──────────┘
//  args.length = 3

The ThreeStoogesDriver pattern — always guard with args.length

public static void main(String[] args) {

    // ALWAYS check length before accessing rooms!
    if (args.length >= 3) {
        // Safe: we know rooms 0, 1, 2 exist
        stooges.add(capitalizeName(args[0]));  // Room 0 → "Moe"
        stooges.add(capitalizeName(args[1]));  // Room 1 → "Larry"
        stooges.add(capitalizeName(args[2]));  // Room 2 → "Curly"
    } else {
        // args.length < 3 — the caller didn't fill enough rooms
        System.out.println("Insufficient command-line data! Defaults used!");
        stooges.add("Moe");
        stooges.add("Larry");
        stooges.add("Curly");
    }

} // end main

Notice: args (a primitive array) feeds directly into an ArrayList<String>. This is the exact pattern you will study again in Kata #3 — The Bridge. For now, focus on args.length and the args[i] access pattern.

Gotcha — Never Access args[0] Without Checking First

If a user runs java MyProgram with no arguments, args.length is 0 and the motel is empty. Accessing args[0] without a length check throws ArrayIndexOutOfBoundsException. Always guard first.

The Indexed for Loop — use when you need the room number

String[] stooges = {"Moe", "Larry", "Curly"};

for (int i = 0; i < stooges.length; i++) {
    System.out.println("Room " + i + ": " + stooges[i]);
}
// Output:
// Room 0: Moe
// Room 1: Larry
// Room 2: Curly
Use the indexed loop when: you need to know the room number (index), modify elements, compare adjacent elements, work with two arrays in parallel, or fill the array with calculated values.

The Enhanced for Loop — use when you only need the value

String[] stooges = {"Moe", "Larry", "Curly"};

for (String stooge : stooges) {
    System.out.println(stooge);
}
// Output:
// Moe
// Larry
// Curly
Use the enhanced for when: you just need each value in order, you do not need the index, and you are not modifying the array elements. Cleaner, less error-prone — but you lose access to the room number.
Gotcha — Enhanced for Cannot Modify Array Contents

The loop variable is a copy of the array element, not a reference to it. Assigning to the loop variable does NOT change the array. Use the indexed loop when you need to write to rooms.

These five patterns appear in nearly every APCS-A free-response set. Drill them until writing them feels like checking in another guest.

Find the Maximum (and Minimum)

int[] scores = {72, 95, 88, 61, 99, 54};

int max = scores[0]; // assume Room 0 holds the max — start there
for (int i = 1; i < scores.length; i++) { // start at Room 1
    if (scores[i] > max) max = scores[i];
}
// max = 99

// For minimum: replace > with <

Sum & Average

int sum = 0;
for (int score : scores) sum += score; // accumulator pattern

double average = (double) sum / scores.length; // cast prevents integer division!

Count Occurrences (Linear Search)

int target = 88;
int count  = 0;
for (int score : scores) {
    if (score == target) count++;
}
// count = 1 (88 appears once)

Fill With Calculated Values

int[] evens = new int[5];
for (int i = 0; i < evens.length; i++) {
    evens[i] = (i + 1) * 2;  // 2, 4, 6, 8, 10
}
// Must use indexed loop — enhanced for cannot write to array rooms

Reverse a Copy

int[] original = {1, 2, 3, 4, 5};
int[] reversed = new int[original.length];

for (int i = 0; i < original.length; i++) {
    reversed[i] = original[original.length - 1 - i];
}
// original: {1, 2, 3, 4, 5}
// reversed: {5, 4, 3, 2, 1}

New Java programmers almost always try to print an array with System.out.println(arr). It compiles. It runs. And it prints something completely useless. This is one of the most reliable ways to waste time debugging.

int[]    nums   = {1, 2, 3, 4, 5};
char[]   vowels = {'a', 'e', 'i'};

System.out.println(nums);    // SURPRISE: [I@4aa298b7  ← memory address!
System.out.println(vowels);  // SURPRISE: aei          ← only char[] works!
Danger Will Robinson — println() and Arrays

System.out.println() calls toString() on the array object. For most array types, the default toString() returns a memory address hash ([I@4aa298b7 for int[]). The [I means “array of integers.” The rest is a hex address. It is never useful output.

char[] is the only exception — it has a special println() overload that actually prints the characters.

Fix: Always use Arrays.toString(arr) for a readable output. See Section 07.

import java.util.Arrays; // required!

System.out.println(Arrays.toString(nums));   // [1, 2, 3, 4, 5]  ← correct!
System.out.println(Arrays.toString(vowels)); // [a, e, i]        ← correct!

⚡ Superpower Unlock

The Arrays class (java.util.Arrays) is a toolkit of static utility methods for working with primitive arrays. It does not add methods to the array itself — it is a separate class you call like Arrays.sort(arr). Think of it as the motel management company: the rooms are still the same old motel, but now you have a professional crew to sort the guests, search for someone, and copy the floor plan.

Import required: import java.util.Arrays;

Method What it does Return Key notes
Arrays.toString(arr) Returns readable string of all elements String Fix for the println gotcha; wraps output in [ ]
Arrays.sort(arr) Sorts array in ascending order void In-place! No new array returned. Original is changed.
Arrays.sort(arr, from, to) Sorts a range [from, to) void to is exclusive
Arrays.binarySearch(arr, val) Finds index of val using binary search int Array MUST be sorted first! Undefined behavior if not sorted.
Arrays.fill(arr, val) Sets every room to the same value void In-place. Useful for resetting an array.
Arrays.copyOf(arr, len) Returns a new array, first len elements new array If len > arr.length, pads with default values
Arrays.copyOfRange(arr, from, to) Returns slice from index from to to new array to is exclusive
Arrays.equals(a, b) Returns true if both arrays have same elements in same order boolean Never use == to compare arrays

Live examples:

import java.util.Arrays;

int[] nums = {5, 3, 8, 1, 9, 2};

System.out.println(Arrays.toString(nums));  // [5, 3, 8, 1, 9, 2]

Arrays.sort(nums);                           // modifies nums IN PLACE
System.out.println(Arrays.toString(nums));  // [1, 2, 3, 5, 8, 9]

int idx = Arrays.binarySearch(nums, 8);     // 4  (index of 8 in sorted array)

Arrays.fill(nums, 0);                        // {0, 0, 0, 0, 0, 0}

int[] first3 = Arrays.copyOf(nums, 3);      // {0, 0, 0}  ← new array

Exam-Day Reference

Kata #1 Quick Reference

Know every row in this table cold before the AP exam.

Operation Syntax Notes / Gotchas
Declare with values int[] arr = {1, 2, 3}; Initializer list — size inferred automatically
Declare with size int[] arr = new int[5]; All rooms set to 0; size is fixed forever
Get size arr.length ⚠ Field, NOT a method — no parentheses!
Get element arr[i] 0-indexed. Valid: 0 → arr.length−1
Set element arr[i] = value; Must use indexed for loop to set elements
Last element arr[arr.length - 1] ⚠ arr[arr.length] is ALWAYS out of bounds
Indexed for loop for (int i = 0; i < arr.length; i++) Use when you need index or modify elements
Enhanced for loop for (int x : arr) Use for read-only traversal; no index available
Print readable Arrays.toString(arr) ⚠ println(arr) prints memory address for int[]!
Sort (ascending) Arrays.sort(arr); In-place, void. Original array is modified.
Binary search Arrays.binarySearch(arr, val) ⚠ Array MUST be sorted first!
Fill all rooms Arrays.fill(arr, val); Sets every element to val. In-place, void.
Copy first N elements Arrays.copyOf(arr, N) Returns NEW array — original unchanged
Copy a range Arrays.copyOfRange(arr, from, to) to is exclusive. Returns NEW array.
Compare two arrays Arrays.equals(a, b) ⚠ Never use == to compare arrays (compares references)
Import import java.util.Arrays; Required for all Arrays class methods
Kata #1 of 7+  •  Primitive Arrays & Arrays Class
Completed this kata? Close the page and write the Quick Reference from memory.