Finding the Index of a String in Another String - Example 1
Snippet: Finding the Index of a String in Another String
Explanation
This snippet introduces the indexOf() method, which searches for a substring inside a String and returns the index of its first character. "Hello" starts at index 0, and "World" starts at index 6.
When the substring is not found — as with "Moon" — indexOf() returns -1. This is a standard convention in Java: a return value of -1 means "not found", and it is a useful signal you can check in your code.
What You Can Do
Try searching for a single character, like "o". What index do you get? Is it the first or last 'o' in the string?
You can also combine indexOf() with substring() — for example, use indexOf("World") to find where "World" starts, then pass that index to substring(). Can you extract "World!" without hardcoding the index 6?
Run it and observe the output!
Example List
Additional Resources
- Learn: Declaring Strings
- Learn: Constructing a String
- Learn: Introduction to String Indexing
- Learn: Comparing Two String Objects Using compareTo Methods
- Learn: Comparing String Objects with equals Methods
- Learn: Obtaining Substrings from a String Object
- Learn: Using the split method on a String
- Practice: Evaluating Expressions that use the String Class
- Practice: Writing Code Using the String Class
- FRQ Practice: AP Computer Science A FRQ 1 Formatting Words
- FRQ Practice: AP Computer Science A FRQ 1 Sentence Analysis