5.2 Index and length

Array Index and length in Java

Unit 5: Arrays · Lesson 5.2 · about 30 minutes · no coding experience needed

This is the lesson that decides whether Unit 6 goes smoothly or is a fortnight of red error messages. It is one rule, and you have already met it three times without the word array.

What you will be able to do

  • Read and write a single element by index
  • Use length correctly, without parentheses
  • Explain the last valid index and read an out-of-bounds message

Words you will need

Index
In plain words Which slot. Counting from 0.
More precisely The integer position of an element, from 0 to length-1.
length
In plain words How many slots. A field, not a method.
More precisely The fixed number of elements, accessed as a.length with no parentheses.

Build it step by step

Every step below leaves a scenario that compiles and runs. If you stop halfway you will have something that works, not something broken. Follow along in Greenfoot rather than reading straight through.

  1. Step 1

    On your screen An array diagram with each slot labeled with its index below it.

    int[] lanes = {3, 7, 2, 9};
    lanes[0]   // 3
    lanes[1]   // 7
    lanes[3]   // 9

    Square brackets after the name pick a slot.

    `lanes[0]` is the FIRST one. The index is not "which position counting from one", it is "how far along from the start", and the first element is zero steps along.

    That phrasing is worth adopting. It makes 0 feel correct rather than arbitrary.

  2. Step 2

    On your screen An assignment into a specific array slot.

    lanes[2] = 5;
    // lanes is now {3, 7, 5, 9}

    An indexed slot behaves exactly like a variable. You can read from it and assign into it with `=`.

    Nothing new. `lanes[2]` is just a name for one particular box.

  3. Step 3

    On your screen The length field being used, contrasted with the size method of a List.

    int[] lanes = {3, 7, 2, 9};
    lanes.length      // 4, NO parentheses
    
    List es = getObjects(Enemy.class);
    es.size()         // parentheses, because it is a method

    Arrays use `length` with NO parentheses. Lists use `size()` WITH parentheses.

    There is no logic to remember here that would help you. It is an inconsistency in Java, and everybody gets it wrong sometimes. If `length()` fails, drop the parentheses; if `size` fails, add them.

  4. Step 4

    On your screen An ArrayIndexOutOfBoundsException with the offending index visible in the message.

    int[] lanes = {3, 7, 2, 9};   // length 4
    lanes[4];                     // THROWS: index 4 out of bounds for length 4

    Length 4 means the last valid index is 3. Asking for 4 throws.

    Read the message: it names the index you tried AND the length. When the index is exactly the length, as here, you have the classic off-by-one and the fix is almost always changing `<=` to `<` in a loop.

    You have met this rule three times already: world coordinates run 0 to width-1, getRandomNumber(n) never gives n, and `i < n` stops at n-1. Same rule, fourth costume.

Mistakes almost everyone makes here

These are the wrong ideas students actually build at this point. Read them even if you think you understand, because a wrong idea you have not noticed is the expensive kind.

Common wrong idea `a[a.length]` is the last element.

What is actually true It is one PAST the last, and it throws. The last is `a[a.length - 1]`.

Why it matters The single most common array error there is.

Common wrong idea length is a method, so it needs parentheses.

What is actually true For an array it is a field: `a.length`. Lists use `size()`.

Why it matters Java is genuinely inconsistent, and students assume they are misremembering.

Common wrong idea ArrayIndexOutOfBoundsException means the array is broken.

What is actually true It means you asked for a slot that does not exist. The array is fine.

Why it matters Students rebuild working arrays instead of fixing the index.

Common wrong idea Negative indexes count from the end.

What is actually true They throw. Java has no such feature.

Why it matters True in some other languages, and a reasonable guess that fails immediately.

Check your understanding

Answer these before moving on. They are graded instantly and you can retry.

  1. 1. `int[] a = {10, 20, 30};` What is `a[1]`?

  2. 2. An array has length 6. What is the last valid index?

  3. 3. How do you get the number of slots in an array called grid?

  4. 4. `int[] a = new int[3]; a[3] = 9;` What happens?

  5. 5. How do you read the LAST element of an array called a?

Fill in the code

Read the first and last elements of an array called lanes, without assuming how long it is.

int first = lanes[];
int last  = lanes[lanes.  1];
Stuck? Open a hint for each blank
  • Blank 1: How far along from the start is the very first element?
  • Blank 2: The number of slots. Remember whether it takes parentheses.
  • Blank 3: The last index is one less than that.

Lesson quiz

This one counts toward your progress. Take it when the section above makes sense.

  1. 1. An array of length 8 has valid indexes:

  2. 2. Which is correct for an array?

  3. 3. A message says "index 5 out of bounds for length 5". What is the likely fix?

  4. 4. What does `a[-1]` do in Java?

The short version

  • Index 0 is the first element. Think "how far along from the start".
  • The last valid index is length - 1.
  • Arrays use `length` with NO parentheses. Lists use `size()` WITH parentheses.
  • An index equal to the length is the classic off-by-one.

If you get stuck

These pages cover the problems that come up most often in this lesson. Opening one is not cheating and it is not counted against you.

Get in Touch

Whether you're a student, parent, or teacher — I'd love to hear from you.

Just want free AP CS resources?

Enter your email below and check the subscribe box — no message needed. Students get daily practice questions and study tips. Teachers get curriculum resources and teaching strategies.

Typically responds within 24 hours

Message Sent!

Thanks for reaching out. I'll get back to you within 24 hours.

🏫 Welcome, fellow educator!

I offer curriculum resources, practice materials, and study guides designed for AP CS teachers. Let me know what you're looking for — whether it's classroom materials, a guest speaker, or Teachers Pay Teachers resources.

Email

[email protected]

📚

Courses

AP CSA, CSP, & Cybersecurity

Response Time

Within 24 hours

Prefer email? Reach me directly at [email protected]