Skip Top Navigation Bar

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