In Java, a substring is a portion of a string extracted from the original string. The String class provides methods like substring() to extract substrings efficiently. Substrings are immutable, just like strings in Java.
substring() Method
The substring() method is used to extract a part of the string, starting at a specific index and optionally ending at another index.
Method Signatures
- substring(int beginIndex)
- Extracts the substring starting from beginIndex to the end of the string.
- substring(int beginIndex, int endIndex)
- Extracts the substring from beginIndex (inclusive) to endIndex (exclusive).
Examples of substring()
1. Extracting with Start Index
String str = “Hello World”;
String result = str.substring(6); // “World”
System.out.println(result);
- Starts extraction at index 6.
- Includes all characters until the end of the string.
2. Extracting with Start and End Index
String str = “Hello World”;
String result = str.substring(0, 5); // “Hello”
System.out.println(result);
- Extracts characters from index 0 to 4 (5 is exclusive).
3. Edge Cases
- Empty Substring: If beginIndex == endIndex, the substring is empty:
String str = “Hello”;
String result = str.substring(2, 2); // “”
System.out.println(result.isEmpty()); // true
- Entire String: If beginIndex == 0 and endIndex == str.length(), the result is the original string:
String str = “Hello”;
String result = str.substring(0, str.length()); // “Hello”
System.out.println(result);
- Error Cases:
- beginIndex < 0
- endIndex > str.length()
- beginIndex > endIndex These cases throw a StringIndexOutOfBoundsException:
String str = “Hello”;
System.out.println(str.substring(-1, 3)); // Exception
Applications of substring()
1. Extracting a Portion of a String
String email = “user@example.com”;
String domain = email.substring(email.indexOf(‘@’) + 1);
System.out.println(domain); // “example.com”
2. Parsing Strings
String data = “ID:12345;Name:John”;
String id = data.substring(3, 8); // “12345”
System.out.println(id);
3. Reversing a Substring
String str = “abcdef”;
String reversed = new StringBuilder(str.substring(1, 4)).reverse().toString();
System.out.println(reversed); // “cba”
Performance Considerations
- Memory Efficiency (Before Java 7u6):
- Substrings shared the original string’s char[] array, which saved memory but could retain unused parts of the string.
- Example:
String str = “Hello World”;
String sub = str.substring(6);
Here, sub references the same character array as str.
- Independent Substring (Java 7u6+):
- Substrings now have their own char[] array, preventing memory leaks but using more memory for the substring.
Using Substring with Loops
To extract multiple substrings, you can use a loop:
Example:
String str = “abcdefgh”;
int length = 3;
for (int i = 0; i < str.length(); i += length) {
String part = str.substring(i, Math.min(i + length, str.length()));
System.out.println(part);
}
Output:
abc
def
gh
Difference Between substring() and split()
Feature | substring() | split() |
Purpose | Extracts a part of the string based on indices. | Divides the string into parts based on a delimiter. |
Input | Indexes (beginIndex, endIndex). | Regular expression or delimiter. |
Output | A single string. | An array of strings. |
Example:
String str = “apple,banana,cherry”;
String sub = str.substring(6, 12); // “banana”
String[] parts = str.split(“,”); // [“apple”, “banana”, “cherry”]
Common Mistakes
- Index Out of Bounds: Ensure beginIndex and endIndex are valid:
String str = “Hello”;
String result = str.substring(10); // Throws exception
- Overlapping Indexes: If beginIndex > endIndex, an exception occurs:
String str = “Hello”;
String result = str.substring(3, 2); // Exception
Example Code
public class SubstringExample {
public static void main(String[] args) {
String str = “Java Programming”;
// Extract “Java”
System.out.println(str.substring(0, 4)); // “Java”
// Extract “Programming”
System.out.println(str.substring(5)); // “Programming”
// Extract “Program”
System.out.println(str.substring(5, 12)); // “Program”
// Error: Out of bounds
try {
System.out.println(str.substring(20)); // Exception
} catch (StringIndexOutOfBoundsException e) {
System.out.println(“Invalid index: ” + e.getMessage());
}
}
}
Output:
Java
Programming
Program
Invalid index: begin 20, end 16, length 16
Conclusion
- The substring() method is a powerful tool for extracting parts of a string in Java.
- It supports a variety of use cases, from simple text manipulation to complex parsing tasks.
- Use it carefully to avoid common pitfalls like invalid indexes or overlapping bounds.