# How Do You Find and Fix Java Array Off-by-One Errors?

Fix Java array off-by-one errors by looping while `i < array.length`, then test an empty array, a one-element array, and an array where only the last value matters. Java starts indexing at zero, so the last valid index of a nonempty array is `array.length - 1`.

> **Quick summary:** To test a method that counts scores of 70 or higher, try `[]`, `[70]`, and `[55, 60, 90]`. The expected counts are `0`, `1`, and `1`. These small cases expose bugs that a longer input can make harder to diagnose.

## Why does `i <= array.length` cause an error?

`i <= array.length` lets the loop reach an index equal to the array’s length, which is outside the array. For `[55, 60, 90]`, the length is `3`, but the valid indices are `0`, `1`, and `2`. Trying to read index `3` throws an `ArrayIndexOutOfBoundsException`.

There’s a quieter bug in the other direction. If you use `i < array.length - 1`, the loop stops before reading the last value. It doesn’t throw an exception. It just gives you the wrong answer when that last value matters. That’s why testing only for crashes can miss an off-by-one error. [College Board’s AP Computer Science A course and exam description](https://apcentral.collegeboard.org/media/pdf/ap-computer-science-a-course-and-exam-description.pdf)

## How do you test array bounds without JUnit?

Write a small method with a clear rule, then call it with inputs whose correct answers you can work out by hand. Here, `countAtLeast` returns how many scores meet or exceed a threshold.

There are two comparisons to test. The loop uses `<` to stay within the array. The score check uses `>=` to include a score equal to the threshold. A mistake in either comparison can give you the wrong result, but for different reasons.

Save this as `ArrayBoundaryTest.java`.

```java
public class ArrayBoundaryTest {
    static int countAtLeast(int[] values, int threshold) {
        int count = 0;

        for (int i = 0; i < values.length; i++) {
            if (values[i] >= threshold) {
                count++;
            }
        }

        return count;
    }

    static void check(String name, int expected, int actual) {
        if (expected != actual) {
            throw new AssertionError(
                name + ": expected " + expected + ", got " + actual
            );
        }
        System.out.println("PASS: " + name);
    }

    public static void main(String[] args) {
        check("empty array", 0, countAtLeast(new int[]{}, 70));
        check("one value meets threshold", 1, countAtLeast(new int[]{70}, 70));
        check("one value below threshold", 0, countAtLeast(new int[]{69}, 70));
        check("only the last value qualifies", 1, countAtLeast(new int[]{55, 60, 90}, 70));
        check("all values qualify", 3, countAtLeast(new int[]{70, 75, 90}, 70));
    }
}
```

Run the file from your terminal. I tested it on Java 21.

```bash
java ArrayBoundaryTest.java
```

You should see five passing checks.

```text
PASS: empty array
PASS: one value meets threshold
PASS: one value below threshold
PASS: only the last value qualifies
PASS: all values qualify
```

## Which test catches each mistake?

The empty array catches a loop that tries to run when there’s nothing to read. The one-element array catches a loop that skips its only value. A score of exactly 70 catches a different mistake, using `>` when the requirement says “at least.”

Change one line at a time and rerun the file. The program stops at the first failure, so restore the correct version before trying the next change.

| Change to try | Expected first failure | What it tells you |
| --- | --- | --- |
| `i <= values.length` | The empty array throws `ArrayIndexOutOfBoundsException`. | The loop tries to read index `0` even though there are no elements. |
| `i < values.length - 1` | The one-element array returns `0` instead of `1`. | The loop stops before reading the final element. |
| `values[i] > threshold` | The score of `70` returns `0` instead of `1`. | The loop may be fine. The score comparison wrongly excludes equality. |

If a test fails without an exception from the loop itself, trace what the code actually visits. With `i < values.length - 1` and the array `[55, 60, 90]`, it reads `55` and `60`, then stops. Since `90` is the only qualifying score, the method returns `0` instead of `1`. That input isolates the bug better than an array where several earlier values also qualify.

## When should you use an enhanced `for` loop instead?

Use an enhanced `for` loop when you need each value but not its index. This method could use `for (int value : values)` and compare `value` to the threshold. You’d avoid writing the index bound yourself.

Keep an indexed loop when the task asks for a position, compares neighbours, or updates an element at a specific index. For your next array exercise, write the empty, one-element, and last-element test cases before you write the loop. If a test fails, you’ll have a clearer idea of where to look.

## Frequently asked questions

### Does an empty Java array have an index `0`?

No. An empty array has length `0` and no valid indices. A loop starting at `0` with the condition `i < array.length` correctly runs zero times.

### Does Java use `.length` or `.length()` for arrays?

Arrays use the field `.length`, without parentheses. A `String` uses `.length()`. An `ArrayList` uses `.size()`.

### Do these tests need JUnit or the `-ea` flag?

No. The `check` method throws `AssertionError` directly when a result is wrong. It doesn’t use Java’s `assert` statement, so the `-ea` flag isn’t needed.

I run EduShaale. If you’re learning to trace Java loops and test your solutions under exam conditions, you can explore [EduShaale’s AP Computer Science A course](https://www.edushaale.com/ap-computer-science-a).
