substring() and indexOf()In Java, a String is a sequence of characters. Each character has a position number called an index.
String word = "computer";
| Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|---|
| Char | c | o | m | p | u | t | e | r |
indexOf() MethodindexOf() finds the position (index) of a character or substring inside a String.
stringName.indexOf(value)
String word = "computer";
int pos1 = word.indexOf("c"); // 0
int pos2 = word.indexOf("p"); // 3
int pos3 = word.indexOf("er"); // 6
int pos = word.indexOf("z"); // -1
indexOf() returns -1, the character or substring does not exist in the String.
substring() Methodsubstring() extracts part of a String.
substring()stringName.substring(startIndex)
This returns everything from the start index to the end of the String.
String word = "computer";
String part = word.substring(3);
System.out.println(part);
puter
stringName.substring(startIndex, endIndex)
String word = "computer";
String part = word.substring(1, 4);
System.out.println(part);
omp
Indexes used: start at index 1 (o) and stop before index 4.
substring() Visual ExampleString text = "JavaProgramming";
| Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|---|
| Char | J | a | v | a | P | r | o | g |
text.substring(0, 4); // "Java"
text.substring(4, 11); // "Program"
indexOf() with substring()These methods are often used together.
String email = "student@school.com";
int atIndex = email.indexOf("@");
String username = email.substring(0, atIndex);
System.out.println(username);
student
word.substring(1, 3);
This gives characters at index 1 and 2 (end index not included).
indexOf() Always Finds Somethingint pos = word.indexOf("z"); // -1
word.substring(pos); // ERROR
✅ Always check first:
if (pos != -1) {
// safe to use pos
}
word.substring(0, word.length()); // entire string
word.substring(0, word.length() - 1); // removes last character
Given:
String msg = "HelloWorld";
msg.indexOf("W");
msg.substring(5);
msg.substring(0, 5);
| Method | Purpose |
|---|---|
indexOf() |
Finds the position of a character or substring |
substring(start) |
Gets text from start index to the end |
substring(start, end) |
Gets text between indexes (end not included) |
| Indexes | Start at 0 |
| End index | Not included |