The substring() is a built-in method of Java’s standard String class. You can use/apply this method on any given string. As a result, it extracts and retrieves a substring(part of a string) according to the specified starting and ending indexes. It is crucial to note that the substring() method doesn’t modify/change the actual string(because strings are immutable), instead, it creates and retrieves a new string.
This method is available in two different variants, which will be discussed in this post using examples.
How to Use String substring() Method in Java
To use the substring method in Java, you must employ the dot syntax, as shown in the below snippet:
//first variant
inputStr.substring(int startIndex);
//second variant
inputStr.substring(int startIndex, int endIndex);
The above syntax shows that the substring() method has two variants: the first one accepts only one parameter while the other one accepts two parameters. The parameters’ details are listed below:
- “stratIndex” represents the start point of the substring (from where the string extraction begins). If you use the first syntax, the substring will be extracted from the stratIndex till the string’s last index.
- The “endIndex” represents the endpoint of the substring (if specified, the substring will be extracted from stratIndex till the endIndex).
- The “inputStr” is the target string from which the substring will be extracted based on the specified parameters.
- The “stratIndex” is inclusive while the “endIndex” is not included(exclusive). For instance, if you specify startIndex “3” and endIndex “6”, then the string will be extracted/retrieved from the third to fifth index.
Warning: While using the substring() method, specify the parameters’ values carefully, otherwise you may face the “StringIndexOutOfBoundsException”. The following factors cause the stated exception:
- If you specify the “startIndex” as greater than the “endIndex”.
- If you specify/provide a negative value(index) for the “startIndex”.
- If the specified startIndex or endIndex of the substring is greater than the actual string’s length.
Let’s understand this method using examples.
Example 1: Extracting Substrings From a String
In the following code, we use the substring() method to extract different substrings from the input string:
public class ExtractSubstrings {
public static void main(String[] args) {
String inputString = "Welcome to JavaBeat.net";
int stringLen = inputString.length();
//Using Substring() With one Parameter
System.out.println("String Characters From Index 11 Onwards: " + inputString.substring(11));
System.out.println("Extracting Domain Extension: " + inputString.substring(stringLen - 4));
//Using Substring() With two Parameters
System.out.println("Extracting Domain Name: " + inputString.substring(11, stringLen));
System.out.println("Extracting a Specific Substring: " + inputString.substring(11, 15));
}
}
In this code,
- We declared a variable “inputString” and initialized it with the value “Welcome to JavaBeat.net”.
- Next, we compute the string length and store it in a variable “stringLen”.
- After this, we use the substring() method which will skip the first ten characters and retrieve the remaining substring.
- Similarly, we use the substring() method one more time to get the last four characters of the input string.
- Up next, we use the substring() method with two parameters to extract a substring between two indexes.
On execution, we get the following resultant output:
Example 2: Extracting All Substrings of a String
You can use the substring() method to get/extract all possible substrings from any given string:
public class ExtractSubstrings {
public static void extractSubstring(String string, int length){
for (int i = 0; i < length; i++)
for (int j = i+1; j <= length; j++)
System.out.println(string.substring(i, j));
}
public static void main(String[] args) {
String inputString = "Java";
int stringLength = inputString.length();
System.out.println("The Possible Substrings of the Given Strings Are:");
extractSubstring(inputString, stringLength);
}
}
In this example,
- We create a user-defined “extractSubstring()” method that accepts a string and the string’s length as an argument.
- Within the extractSubstring() method, we use a nested for loop to iterate the given string from the start to end and extract each possible substring.
- In the end, we invoke the “extractSubstring()” method from the main() method and pass the input string and its total length as arguments.
Here is the resultant output:
Example 3: Extracting Substrings From Different Strings and Joining Them
Let’s learn how you can extract substrings of your choice from different strings and combine them to make a single(meaningful) string:
public class ExtractSubstrings {
public static void main(String[] args) {
String string1 = "Welcome to JavaBeat";
String string2 = "Hello, Let's Learn Java";
System.out.println(String.join(",", string1.substring(0, 7), string2.substring(6)));
}
}
Here,
- We are given two strings: string1 and string2.
- We use the substring() method a couple of times on the given strings.
- The first substring() method extracts a substring from the string1 (between index 0 and 7). The second substring() method skips the first 6 characters and retrieves the remaining substring.
- Finally, we wrap both substring() methods within the join() method to combine the extracted substrings. The extracted substrings will be concatenated/joined using a comma “,”:
Example 4: Extracting Substrings Between Different Delimiters
This code example will teach you how to extract substrings between some specific delimiters:
public class ExtractSubstrings {
public static void main(String[] args) {
String inputString = "Let's learn Java with -javabeat.net-";
int startIndex = inputString.indexOf("-");
int endIndex = inputString.lastIndexOf("-");
String substring = inputString.substring(startIndex + 1, endIndex);
System.out.println("The substring between specific delimiters is ==> " +substring);
}
}
In this example,
- We use the indexOf() and lastIndexOf() methods to get the first and last indexes of the “-” delimiter.
- Up next, we invoke the substring() method and pass the index of the first and last occurrence of the “-” delimiter as its argument.
As a result, the substring() method will retrieve the following extracted substring:
Example 5: Finding Palindrome Strings Using substring()
Palindrome strings are strings that look the same when you reverse them. You can use the substring() method to check if the provided string is palindrome or not:
public class ExtractSubstrings {
public static boolean isPalindromeString(String string) {
//if null, return false
if (string == null)
return false;
//if string length is <= 1, return true
if (string.length() <= 1) {
return true;
}
//extracting the first and last characters of the string
String firstChar = string.substring(0, 1);
String lastChar = string.substring(string.length() - 1);
//comparing the first/starting and last/ending characters of the string
if (!firstChar.equals(lastChar))
return false;
else
return isPalindromeString(string.substring(1, string.length() - 1));
}
public static void main(String[] args) {
System.out.println("level is Palindrome? " + isPalindromeString("level"));
System.out.println("Java is Palindrome? " + isPalindromeString("Java"));
System.out.println("1221 is Palindrome? " + isPalindromeString("1221"));
System.out.println("madam is palindrome? " + isPalindromeString("madam"));
System.out.println("null is Palindrome? " + isPalindromeString(null));
}
}
In this code,
- We create a user-defined “isPalindromeString()” method. This method accepts a string and retrieves true if it is a palindrome, and false if it’s not a palindrome.
- Within the “isPalindromeString()” method, we first check if the given string is null. If yes, return “false” straight away.
- If the string has length 1, return “true” because any string that has only one character is always a palindrome.
- After this, we use the substring() method to extract one character from the start/left side and one character from the end/right side of the given string.
- Up next, we employ the equals() method to compare the extracted characters/letters.
This way, all characters will be compared and a boolean true will be returned if the provided string is a palindrome:
Example 6: Removing the First and Last Characters of a String
You can also use the substring() method to remove unnecessary/unwanted characters from the start and end of the string. Here is the practical demonstration of the stated concept:
public class ExtractSubstrings {
public static void main(String[] args) {
String string = "-Let's learn Java with javabeat.net-";
System.out.println("Removing First Character from the inputString: " + string.substring(1));
System.out.println("Removing First Character from the inputString: " + string.substring(0, string.length() - 1));
}
}
In this code snippet,
- In the first statement, we use “substring(1)” to remove the first character of the string.
- We use the substring() method one more time. But this time, we use this method with two parameters: “0”, and “string.length() – 1”.
- This way, the substring() method will extract a substring from the 0th index to the second last index.
Example 7: Extracting Words From a String Based on a Specific Token
In the following example, we have a string that contains a “-” token after each word. We will show you how to break this string into different substrings based on the token “-”:
public class ExtractSubstrings {
public static void main(String[] args) {
String inputString = "Hello-welcome-to-Java-tutorials";
for(int startIndex = 0; startIndex < inputString.length() ; ) {
int tokenIndex = inputString.indexOf('-', startIndex);
if(tokenIndex == -1) {
tokenIndex = inputString.length();
}
String substring = inputString.substring(startIndex, tokenIndex);
System.out.println("Extracted Substring => " + substring);
startIndex = tokenIndex + 1;
}
}
}
In the above code,
- First, we execute a for loop to traverse the given string.
- Within the loop, we invoke the indexOf() method to locate the targeted token’s index. This method will return “-1” if the specified token isn’t found in the given string. In that case, the index of the token will be the last/final index of the string. This way, the whole string will be retrieved as one substring.
- After this, we employ the substring() method to extract/get the substrings based on the selected token.
- Finally, we increment the value of the “tokenIndex” variable by 1.
The below screenshot shows the final output:
This sums up the practical implementation of the “substring()” method in Java.
Final Thoughts
To use the String substring() method in Java, follow the syntax “inputString.substring(int startIndex);” or “inputStr.substring(int startIndex, int endIndex);”. In case, you execute the first variant, then the string will be extracted from the specified startIndex to the last index of the given string. On the other hand, the second variant is much more flexible and allows you to extract a substring between the indexes of your choice. The choice of each variant depends on your needs, as demonstrated in the above-given examples.