substring()
Learn Java substring() method to extract parts of strings using startIndex & endIndex. Master string manipulation, handle edge cases like IndexOutOfBounds, and optimize performance. Complete tutorial with examples for Java developers.
A substring is just a smaller part of a larger string. Java provides the substring()
method to help you extract parts of a string. You can use this method to grab certain sections, like the first few characters of a string or everything after a specific position.
Let us see how substring()
works, some edge cases to watch out for, and performance considerations.
How to use?
The substring()
method allows you to extract a part of a string by specifying start and (optionally) end positions.
Syntax:
String result = originalString.substring(startIndex);
String result = originalString.substring(startIndex, endIndex);
- startIndex: The position where the substring begins (inclusive).
- endIndex: The position where the substring ends (exclusive). If not provided, it will extract everything from
startIndex
to the end of the string.
Example 1: Extracting a Substring from a Specific Position:
String text = "Hello, World!";
String subText = text.substring(7); // "World!"
In this example, the substring starts at position 7 and goes to the end of the string. So "World!"
is extracted.
Example 2: Extracting a Substring Between Two Positions:
String text = "Hello, World!";
String subText = text.substring(0, 5); // "Hello"
Here, we extract from index 0 (the start) to index 5 (not including 5). The result is "Hello"
.
Edge Cases in substring()
When working with the substring()
method, there are a few edge cases to be aware of, especially when dealing with invalid indexes or empty strings.
- Index out of bounds
- Start index greater than end index.
- Empty strings
- Extracting the entire string.
Index Out of Bounds
It would be best to consider the start and end indexes valid. If you try to use an index that’s larger than the length of the string or negative, Java will throw a StringIndexOutOfBoundsException
.
Example:
String text = "Hello, World!";
String subText = text.substring(0, 50); // This will throw an exception because 50 is too large
To avoid this, always check that your indexes are within the range of the string:
String text = "Hello";
if (startIndex >= 0 && endIndex <= text.length()) {
String subText = text.substring(startIndex, endIndex);
}
Start Index Greater than End Index
The startIndex
should always be less than or equal to endIndex
. If it’s not, you’ll get an error.
Example:
String text = "Hello";
String subText = text.substring(5, 2); // Throws an error because startIndex > endIndex
Empty Strings
If you extract a substring where the start and end indexes are the same, the result will be an empty string ""
.
Example:
String text = "Hello";
String subText = text.substring(3, 3); // Result: ""
This doesn’t cause an error, but it’s something to be aware of.
Extracting the Entire String
If you use substring(0, text.length())
, you’ll get the entire string, since you're extracting from the start to the end.
Example:
String text = "Hello";
String subText = text.substring(0, text.length()); // Result: "Hello"
Performance Considerations
The substring()
method is generally fast, but there are a few performance details to consider, especially in older versions of Java.
- Memory Usage (Pre-Java 7): Before Java 7, the
substring()
method created a reference to the original string’s internal data, which could cause memory issues if you were dealing with large strings. Even if you extracted a small part of the string, the original string would remain in memory. - Memory Usage (Java 7 and Later): In Java 7 and later, when you extract a substring, a new string is created containing only the characters you requested. This means that no memory is wasted on the original string. However, creating new strings still consumes memory, so if you're extracting many small substrings from a large string, it can add up in terms of memory usage.
- Avoiding Substrings in Loops: If you are extracting numerous substrings within a loop, be cautious about performance. Creating many new strings in each loop iteration can impact efficiency.
Example of inefficient code:
String text = "Hello, World!";
for (int i = 0; i < text.length(); i++) {
String subText = text.substring(i);
}
In this example, you’re creating a new substring in every loop, which can be slow for large strings. In performance-sensitive applications, minimizing the number of new strings you create is best.
Summary
substring()
allows you to extract part of a string by specifying start and (optionally) end positions.- Edge cases include ensuring the indexes are valid, handling empty strings, and avoiding out-of-bounds errors.
- In Java 7 and later,
substring()
creates a new string, so it’s memory efficient compared to older versions. However, avoid excessive substring extraction in loops to maintain performance.
By understanding how substring()
works and being mindful of edge cases, you can safely and efficiently manipulate strings in your Java programs.