How to Find Substring in Java: Syntax and Examples
In Java, you can find a substring using the
indexOf method which returns the position of the substring or -1 if not found. Alternatively, use contains to check if a substring exists, returning a boolean value.Syntax
The main methods to find a substring in Java are:
int indexOf(String substring): Returns the starting index of the substring or -1 if not found.boolean contains(CharSequence sequence): Returnstrueif the substring exists, otherwisefalse.
java
String str = "Hello, world!"; int position = str.indexOf("world"); boolean exists = str.contains("Hello");
Example
This example shows how to find the position of a substring and check if it exists in a string.
java
public class SubstringExample { public static void main(String[] args) { String text = "Welcome to Java programming!"; String search = "Java"; int index = text.indexOf(search); if (index != -1) { System.out.println("Substring '" + search + "' found at index: " + index); } else { System.out.println("Substring not found."); } boolean contains = text.contains(search); System.out.println("Does the text contain '" + search + "'? " + contains); } }
Output
Substring 'Java' found at index: 11
Does the text contain 'Java'? true
Common Pitfalls
Common mistakes when finding substrings in Java include:
- Not checking if
indexOfreturns -1 before using the index. - Confusing
indexOfwithcontains:indexOfreturns an index,containsreturns a boolean. - Case sensitivity: these methods are case sensitive, so "java" and "Java" are different.
java
String text = "Hello World"; // Wrong: Using index without checking int pos = text.indexOf("world"); System.out.println("Position: " + pos); // Outputs -1, but no check // Right: Check before using if (pos != -1) { System.out.println("Found at: " + pos); } else { System.out.println("Not found"); }
Output
Position: -1
Not found
Quick Reference
| Method | Description | Return Type | Example |
|---|---|---|---|
| indexOf(String) | Finds starting index of substring | int | str.indexOf("abc") |
| contains(CharSequence) | Checks if substring exists | boolean | str.contains("abc") |
| substring(int, int) | Extracts substring by index range | String | str.substring(2,5) |
Key Takeaways
Use indexOf to get the position of a substring; it returns -1 if not found.
Use contains to check if a substring exists; it returns true or false.
Always check indexOf result before using it to avoid errors.
Remember substring search is case sensitive in Java.
Use substring method to extract parts of a string by index.