Java String substring() Method with Examples
Get Job-ready: Java Course with 45+ Real-time Projects! - Learn Java
The substring() method of the Java String class is a commonly used string manipulation method. It allows extracting a substring from a larger string by specifying the beginning and ending indices. In this article, we will take an in-depth look at how the substring() works and how it can be used.
The substring() method is defined in the String class and has two variants:
String substring(int beginIndex) String substring(int beginIndex, int endIndex)
The first version takes a single int parameter, beginIndex, that specifies the starting index of the substring. The substring returned will be from beginIndex to the end of the original string.
The second version takes two int parameters – beginIndex and endIndex. This returns the substring from beginIndex to endIndex-1.
Note that the endIndex is exclusive, meaning the character at endIndex is not included in the returned substring. This follows Java’s convention for specifying a range: the beginning index is inclusive, while the ending index is exclusive.
Internal Implementation of Java substring(int beginIndex)
Here is a look at a simplified implementation of the single-parameter substring() method:
public String substring(int beginIndex) {
if (beginIndex < 0 || beginIndex > value.length()) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
int subLen = value.length() - beginIndex;
char[] newValue = Arrays.copyOfRange(value, beginIndex, subLen);
return new String(newValue);
}This performs some sanity checking on beginIndex to ensure it is within bounds. If not, a StringIndexOutOfBoundsException is thrown.
It then calculates the length of the substring, which is from beginIndex to the end of the original string. The substring is created by copying the range from the internal character array (value) into a new array using copyOfRange(). This new array is then used to construct the String to return.
Internal Implementation of Java substring(int beginIndex, int endIndex)
The implementation of the two-parameter version is similar:
public String substring(int beginIndex, int endIndex) {
if (beginIndex < 0 || endIndex > value.length() || beginIndex > endIndex) {
throw new StringIndexOutOfBoundsException();
}
int subLen = endIndex - beginIndex;
char[] newValue = Arrays.copyOfRange(value, beginIndex, subLen);
return new String(newValue);
}It does validity checks on the passed indices to catch any bad values. The length is calculated as endIndex – beginIndex. The character range is copied over into a new array, same as before.
One difference is that it throws a more generic StringIndexOutOfBoundsException on invalid indices.
Examples of Java String substring()
Let’s look at some examples of using substring() in Java:
Example 1: Extracting a substring with begin and end indices
public class SubstringExample {
public static void main(String[] args) {
String str = "HelloWorld";
String sub = str.substring(2, 7);
System.out.println(sub); // Output: lloWo
}
}Output:
lloWo
Here we extract a substring from index 2 (inclusive) to index 7 (exclusive), so it prints “lloWo”.
Example 2: Extracting a substring from the beginning index to the end
public class SubstringExample {
public static void main(String[] args) {
String str = "JavaRules";
String sub = str.substring(4);
System.out.println(sub); // Output: Rules
}
}Output:
Rules
Passing only the starting index returns the substring from that index to the end of the original string.
Applications of Java substring()
Let’s see some practical examples of using substring():
Extracting surnames from full names:
public class SurnameExtraction {
public static void main(String[] args) {
String fullName = "Robert Downey Jr";
int index = fullName.lastIndexOf(' ');
String surname = fullName.substring(index + 1);
System.out.println(surname); // Output: Downey
}
}Output:
Downey
Checking if a string is a palindrome:
public class PalindromeCheck {
public static void main(String[] args) {
String word = "racecar";
String reversed = new StringBuilder(word).reverse().toString();
if (word.equals(reversed)) {
System.out.println(word + " is a palindrome");
}
}
}Output:
racecar is a palindrome
Conclusion
To sum up, the Java String. substring() method is a versatile tool for extracting and manipulating substrings. It provides developers with the flexibility to specify both the start and end points of the desired substring using two parameter variants. The method’s internal implementation ensures proper bounds checking and adheres to Java’s exclusive-end-index convention.
With practical applications ranging from extracting surnames to checking for palindromes, substring() remains a valuable feature in Java’s string manipulation toolkit, enhancing its overall string-processing versatility.
Did you like this article? If Yes, please give DataFlair 5 Stars on Google

