Unit 1 Day 10: String length() and indexOf() Practice
Share
Unit 1, Section 1.10
Day 10 Practice • January 16, 2026
🎯 Focus: String Methods (length & indexOf)
Practice Question
Consider the following code segment:
String word = "Computer";
System.out.println(word.length() + word.indexOf("put"));
What is printed as a result of executing this code segment?
What This Tests: This question tests two essential String methods:
length() which returns the number of characters, and indexOf() which returns the starting position of a substring.Key Concept: String Indexing
Strings are indexed starting at 0:
// Index: 0 1 2 3 4 5 6 7
// String: C o m p u t e r
"Computer".length() // → 8 (count of characters)
"Computer".indexOf("put") // → 4 (where "put" starts)
"Computer".indexOf("xyz") // → -1 (not found)
Step-by-Step Trace
| Expression | Explanation | Result |
|---|---|---|
| word.length() | "Computer" has 8 characters | 8 |
| word.indexOf("put") | "put" starts at index 4 (Computer) | 4 |
| 8 + 4 | Addition | 12 |
Common Mistakes
Mistake: Answer B (11)
This comes from thinking indexOf returns where "put" ends (index 7) rather than where it starts (index 4). indexOf always returns the starting position.
Mistake: Answer D (13)
This might come from counting "put" as starting at position 5 (counting from 1 instead of 0). Remember: Java strings are 0-indexed!
String Methods Reference
💡 Essential String Methods for AP CSA
length() - Returns number of characters
indexOf(str) - Returns index where str starts (-1 if not found)
substring(start) - Returns from start to end
substring(start, end) - Returns from start to end-1
equals(str) - Compares content (case-sensitive)
Related Topics
- Section 1.11: substring() method
- Section 1.8: String concatenation
- Section 2.5: String comparison with equals()
Difficulty: Easy • Time: 1-2 minutes • AP Skill: 2.C - Call methods
Want More Practice?
Master AP CSA with guided practice and expert help
Schedule 1-on-1 Tutoring Practice FRQs