indexOf and substring
- Java course
- Beginner
- Lesson 32/116
- 4 min
Learn searching and slicing with indexOf() and substring().
indexOf and substring
indexOf gives the first position of a substring. If not found, it returns -1. substring takes a slice.
String s = "Hello world";
int i = s.indexOf("wor"); // 6
String part = s.substring(0, 5); // "Hello"substring(start) goes from start to the end; substring(start, end) goes from start to end (exclusive).
Check with if (i != -1) before using the found position.
Searching with indexOf
indexOf gives the first index where a character or substring appears. If not found, it returns -1.
String s = "Java";
int i = s.indexOf('a'); // 1 (first 'a')
int j = s.indexOf('z'); // -1 (not present)If the result is -1, the substring is not present. So if (s.indexOf(x) != -1) is a common pattern.
To find the second occurrence, use the indexOf(x, start) form.
Practice Use indexOf and substring
Write a Main class with a main method. Assign "Hello world" to String s. Print s.indexOf("world") and s.substring(0, 5) with println.
Sample solution
public class Main {
public static void main(String[] args) {
String s = "Hello world";
System.out.println(s.indexOf("world"));
System.out.println(s.substring(0, 5));
}
}Expected output
6 Hello
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the substring call
String part = s.____(0, 5);
String part = s.substring(0, 5);
Explanation: substring(0, 5) takes the first 5 characters.
2 Match the methods
| Term | Meaning |
|---|---|
indexOf |
Search |
substring |
Slice |
length |
Length |
charAt |
Character |
3 What does indexOf return when not found?
- 0
- null
- -1 Correct answer
- false
Explanation: indexOf returns -1 when not found.