StringIndexOutOfBoundsException in Java: charAt & substring (AP CSA)

AP CSAJava Errors › StringIndexOutOfBoundsException
Java Error Help • AP CSA

StringIndexOutOfBoundsException in Java: charAt and substring (AP CSA)

A StringIndexOutOfBoundsException means you asked for a character position that does not exist in a String. Like arrays, String positions run from 0 to length() - 1, and methods like charAt and substring throw when you go past that.

Error type: Runtime exception (compiles fine, then crashes while running).

Plain meaning: You called charAt, substring, or a similar method with a position outside the String.

Fastest fix: Remember the last valid character index is length() - 1, and loop with i < s.length().

Why students see this error

A String is an indexed sequence of characters numbered from 0. The string "cat" has length 3 and valid indexes 0, 1, and 2. Calling charAt(3) asks for a fourth character that does not exist, so Java throws the exception. The same applies to substring when the start or end goes past the end of the String.

  • A loop uses i <= s.length() instead of i < s.length().
  • Calling charAt(s.length()) instead of charAt(s.length() - 1) for the last character.
  • A substring call whose end index is greater than the String's length.

Broken code that triggers it

Throws StringIndexOutOfBoundsException
public class Spell {
  public static void main(String[] args) {
    String word = "cat";   // length 3, indexes 0..2

    for (int i = 0; i <= word.length(); i++) {  // BUG: <=
      System.out.println(word.charAt(i));        // crashes at i = 3
    }
  }
}

The loop allows i to reach 3 because of <=, but "cat" has no character at index 3 (valid indexes are 0, 1, 2). On the pass where i is 3, charAt(3) throws the exception.

Trace: watch where it breaks

Trace the index against the valid range of the String:

i i <= 3 ? word.charAt(i) Result
0 true 'c' prints c
1 true 'a' prints a
2 true 't' prints t
3 true (no index 3) StringIndexOutOfBoundsException

Each existing character prints fine. The fault is the loop letting i reach length(), one past the last valid index of length() - 1.

The fix

Runs correctly
public class Spell {
  public static void main(String[] args) {
    String word = "cat";

    for (int i = 0; i < word.length(); i++) {   // < stops at length() - 1
      System.out.println(word.charAt(i));
    }
  }
}

Using i < word.length() stops the loop after the last valid index. The same rule applies to substring(a, b): b may equal length() (it is exclusive), but no index may exceed it.

How College Board tests this concept

AP Connection (Official CED)

String traversal and methods like charAt, substring, indexOf, and length are core to Using Objects and Methods. The exam tests careful index reasoning, especially the boundary at length() - 1.

Read it in the official CED: Unit 1 (CED p.23)

Watch for items that traverse a String with a <= loop, or that mix up substring's inclusive start and exclusive end. The exam often asks for the exact output of a String loop, where one off-by-one step changes everything.

Common MCQ traps (practice set)

Watch out

The trap is treating substring's end index like charAt's index. In substring(start, end), end is exclusive and may equal length(); in charAt(i), i must be strictly less than length().

Question 1: Predict the result

String s = "hi";
System.out.println(s.charAt(2));

What is the result of running this code?

  • A) Prints i
  • B) Prints an empty line
  • C) A StringIndexOutOfBoundsException is thrown
  • D) Prints h
Answer: C. "hi" has length 2, so valid indexes are 0 and 1 only. charAt(2) asks for a third character that does not exist, throwing the exception. A assumes a non-existent index 2 holds 'i', but 'i' is at index 1.

Question 2: substring boundary

Consider these two calls on String t = "code"; (length 4).

I.    t.substring(0, 4)
II.   t.charAt(4)

What are the results?

  • A) I throws; II throws
  • B) I returns "code"; II throws
  • C) I returns "cod"; II returns 'e'
  • D) I throws; II returns 'e'
Answer: B. In substring(0, 4) the end index is exclusive and may equal length(), so it legally returns the whole String "code". But charAt(4) needs a valid index strictly less than 4, so it throws. This contrast between exclusive end and required index is the key idea.

Question 3: Find the last character safely

String w has at least one character.

Which expression returns the last character without throwing?

  • A) w.charAt(w.length())
  • B) w.charAt(w.length() - 1)
  • C) w.charAt(-1)
  • D) w.substring(w.length())
Answer: B. The last valid index is length() - 1, so B is correct. A uses length() (one too high) and throws; C uses a negative index and throws; D returns an empty String, not a character.

Frequently asked questions

What is the last valid index of a String?

It is length() - 1. The String "hello" has length 5 and valid indexes 0 through 4.

Why does substring(0, length()) not throw?

Because substring's end index is exclusive and is allowed to equal length(). It returns the whole String. Only an end index greater than length() throws.

Is this the same as ArrayIndexOutOfBoundsException?

It is the String version of the same idea. Both mean an index outside the valid range, one for Strings and one for arrays.

Master the concepts behind the error

Work through the full AP CSA lessons, then test yourself.

AP CSA Lessons All Java Errors

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]