Arrays — Declaration, Iteration, and Common Operations

8 min read

An array is the simplest container Java offers — a fixed-size, typed sequence of values. You'll use arrays everywhere: a list of browsers to test against, a list of accepted status codes, a row of test data passed to a parameterised test. Java's arrays are stricter than JavaScript's: every element must be the same type, and the size is locked at creation time. The trade is that arrays are fast and predictable — exactly what test data fixtures need. This lesson covers declaration, indexing, the Arrays utility class, and the gotchas you'll meet on day one.

Declaring an array

Two syntaxes — pick the one that fits the situation:

// Literal — known values
String[] browsers = {"Chrome", "Firefox", "Safari", "Edge"};
int[] statusCodes = {200, 201, 204, 301, 404, 500};
boolean[] passed = {true, false, true, true};
 
// Sized — empty array, fill it later
boolean[] results = new boolean[5];   // 5 slots, all false (the default for boolean)
int[] retries = new int[10];           // 10 slots, all 0 (the default for int)
String[] testNames = new String[3];   // 3 slots, all null (the default for object types)

Read String[] as "array of String." The array's type is locked: a String[] cannot hold an int, and an int[] cannot hold a String. The compiler enforces this — pleasantly different from JavaScript, where [200, "OK", true] is a single legal array.

The default values when you use new Type[size] matter:

  • numeric types (int, double, long) default to 0
  • boolean defaults to false
  • object types (String, int[], custom classes) default to null

Length — a field, not a method

The number of elements is arr.length. Note: no parentheses.

String[] browsers = {"Chrome", "Firefox", "Safari"};
System.out.println(browsers.length);   // 3

This is one of Java's tiny quirks: arrays have a length field, but String (and every collection in chapter 6) has a length() method and a size() method respectively. Mixing them up is a constant low-grade compile error you'll learn to read at a glance:

  • arr.length ← arrays
  • str.length() ← Strings
  • list.size()ArrayList and other collections

Indexing — zero-based, like JavaScript

String[] browsers = {"Chrome", "Firefox", "Safari", "Edge"};
 
System.out.println(browsers[0]);   // Chrome  ← first
System.out.println(browsers[3]);   // Edge    ← last
System.out.println(browsers[4]);   // ❌ throws ArrayIndexOutOfBoundsException

Indices run from 0 to length - 1. Going out of range throws ArrayIndexOutOfBoundsException at runtime — Java doesn't return undefined the way JavaScript does. Off-by-one in the loop bound is the most common source of this error, which is one reason the enhanced for loop is so popular:

for (String browser : browsers) {
    System.out.println("Testing on: " + browser);
}

Output:

Testing on: Chrome
Testing on: Firefox
Testing on: Safari
Testing on: Edge

When you don't need the index, prefer this form — there's no off-by-one to get wrong.

Setting and reading

You change an element by assignment, exactly like JavaScript:

String[] browsers = {"Chrome", "Firefox", "Safari", "Edge"};
browsers[1] = "Brave";
System.out.println(browsers[1]);   // Brave

You cannot add or remove elements, however. The size is fixed at creation time. browsers.add("Opera") does not exist. If you need a growable list, use ArrayList<String> from chapter 6.

The Arrays utility class

java.util.Arrays is a class full of static helpers for arrays. Import it once at the top of your file:

import java.util.Arrays;

The methods you'll use most:

import java.util.Arrays;
 
public class ArraysDemo {
    public static void main(String[] args) {
        int[] codes = {404, 200, 500, 301, 200};
 
        Arrays.sort(codes);                                 // mutates in place
        System.out.println(Arrays.toString(codes));         // [200, 200, 301, 404, 500]
 
        int idx = Arrays.binarySearch(codes, 404);          // requires sorted input
        System.out.println("404 is at index: " + idx);
 
        int[] copy = Arrays.copyOf(codes, codes.length);    // independent copy
        copy[0] = 999;
        System.out.println("Original first: " + codes[0]);  // still 200
        System.out.println("Copy first:     " + copy[0]);   // 999
 
        boolean equal = Arrays.equals(codes, copy);         // element-by-element
        System.out.println("Same contents?  " + equal);     // false
 
        int[] zeros = new int[5];
        Arrays.fill(zeros, 1);                              // fill with 1
        System.out.println(Arrays.toString(zeros));         // [1, 1, 1, 1, 1]
    }
}

Output:

[200, 200, 301, 404, 500]
404 is at index: 3
Original first: 200
Copy first:     999
Same contents?  false
[1, 1, 1, 1, 1]

Two things worth noting:

  • Arrays.toString(arr) exists because plain System.out.println(arr) prints garbage like [I@1b6d3586 — Java's default toString on arrays gives you the type and a hash code, not the contents. Whenever you need to debug an array, reach for Arrays.toString.
  • Arrays.equals(a, b) is the right way to compare contents. a == b only checks references (chapter 2.2 again).

A real QA snippet — running and tallying

A combined example that uses arrays and a method:

import java.util.Arrays;
 
public class TestRun {
 
    public static boolean[] runAll(String[] testCases) {
        boolean[] results = new boolean[testCases.length];
        for (int i = 0; i < testCases.length; i++) {
            // pretend we're actually running the test
            results[i] = !testCases[i].startsWith("BROKEN_");
        }
        return results;
    }
 
    public static void main(String[] args) {
        String[] testCases = {"Login", "Search", "BROKEN_Checkout", "Logout", "BROKEN_Export"};
 
        boolean[] results = runAll(testCases);
 
        int passed = 0;
        for (boolean r : results) if (r) passed++;
 
        System.out.println("Cases:   " + Arrays.toString(testCases));
        System.out.println("Results: " + Arrays.toString(results));
        System.out.println("Passed:  " + passed + " / " + testCases.length);
    }
}

Output:

Cases:   [Login, Search, BROKEN_Checkout, Logout, BROKEN_Export]
Results: [true, true, false, true, false]
Passed:  3 / 5

The runAll method takes an array of test names, allocates a results array of the same length with new boolean[testCases.length], walks the input with a classic indexed for loop (because we need to write into results[i]), and returns the populated array. Real test runners do the same shape with richer types.

Anatomy of an array

Four cells, indices 0–3. browsers.length is 4 (the count, not the highest index). browsers[0] is "Chrome". browsers[4] throws ArrayIndexOutOfBoundsException. That mental picture explains every array operation you'll meet.

⚠️ Common mistakes

  • arr.length() instead of arr.length. Arrays use the field; Strings and collections use the method. The compiler error is concrete: cannot find symbol — method length(). The fix is to drop the parentheses on arrays only.
  • println(arr) printing gibberish. System.out.println(browsers) prints something like [Ljava.lang.String;@1b6d3586 — that's the default toString for arrays. For human-readable output, always use Arrays.toString(browsers). There is also Arrays.deepToString(...) for 2D arrays.
  • Assuming Arrays.binarySearch works on unsorted input. It doesn't — the algorithm requires a sorted array, and on unsorted input it returns a misleading negative number that looks like "not found." Always Arrays.sort(...) first, or use a linear search if you can't reorder the data.

🎯 Practice task

Walk a test suite of arrays end to end. 25 minutes.

  1. Create BrowserMatrix.java and import java.util.Arrays;.
  2. In main, declare two arrays:
    • String[] browsers = {"Chrome", "Firefox", "Safari", "Edge"};
    • boolean[] results = {true, true, false, true};
  3. Use a classic indexed for loop to print one line per browser: Chrome -> PASS, Firefox -> PASS, etc. The indices have to align — that's why you use the indexed form here.
  4. Use an enhanced for loop to count how many true values are in results (passed) and print Passed: 3 / 4.
  5. Print both arrays with Arrays.toString(browsers) and Arrays.toString(results). Confirm the output looks like [Chrome, Firefox, Safari, Edge].
  6. Sort browsers with Arrays.sort(browsers) and reprint it.
  7. Make a copy with String[] backup = Arrays.copyOf(browsers, browsers.length);. Reassign browsers[0] = "Brave";. Print both — confirm only one changed (proving copyOf is a real copy, not an alias).
  8. Stretch: try browsers[5] = "Opera"; (deliberately past the end). Read the runtime error. Fix the assignment to be at a valid index — and notice the difference between compile-time and run-time failures. Java catches type mistakes at compile time; out-of-bounds is only checked when the code runs.

Arrays are the foundation. The next lesson stacks them — 2D arrays — to build the test data tables that drive parameterised tests.

// tip to track lessons you complete and pick up where you left off across devices.