A string is a data type that stores a combination of characters and is immutable(can not be modified once declared). However, the user can extract specific parts or characters from the String according to their index position in the String using the “substring()” method. This method also performs operations like extracting data with specific prefixes or suffixes.

This guide covers the usage of a “substring()” method in Java by explaining the following concepts:

How to Use the “substring()” Method in Java?

It accepts an index number as an argument and extracts a substring from the targeted string accordingly. Using this method, the user can remove an element from the first or last index, extract characters after a specified word, etc.

Syntax

There are two syntax variants for the substring() Method both are listed below:

  • Public String substring(int startingPoint)

This accepts only stating index numbers and the extracted String contains all characters from this index number. In code, this variant applies like this:

targetedString.substring(int startingPoint);
  • Public String substring(int startingPoint, int endingPoint)

This variant contains an extra parameter that accepts the ending index till the String gets extracted. Its implementation in code looks like this:

targetedString.substring(int startingPoint, int endingPoint);

In the above syntaxes:

  • The “targetedString” is the one whose substring is going to be created. 
  • The “startingPoint” and “endingPoint” are the indexes from where the character’s extracting process starts and ends.

Note: As indexing always starts from “0”, the value of “endingPoint” must be one factor less (-1). 

Exceptions:

While the utilization of a “substring()” method, the “StringIndexOutOfBoundsException” might occur. The usual causes of its occurrences are stated below:

  • The starting or ending index values are negative.
  • The entered index is greater than the length of an entire String.
  • The ending index is less than the provided starting index.

Let’s explore the implementation of “substring()” method variations.

Variant 1: Public String substring(int startingPoint)

As already discussed, this variant of a “substring()” method accepts only a single argument which is considered as the starting index. From this index number, the String extracting process starts, as shown below:

public class Substring {
public static void main(String[] args) {

  String targetStr = "Implementation of substring Method";

  System.out.println("Passing Valid Starting Index Number: ");
  System.out.println("Extracted part is =>" + targetStr.substring(18));

  System.out.println("\nPassing '0' as Starting Index Number: ");
  System.out.println("Extracted part is =>" + targetStr.substring(0));

  System.out.println("\nPassing String length as Starting Index Number: ");
  System.out.println("Extracted part is =>" + targetStr.substring(targetStr.length()));

  System.out.println("\nRemoval of Single Element From Start: ");
  System.out.println("Extracted part is =>" + targetStr.substring(1));  

  System.out.println("\nPassing invalid or negative Value as Starting Index: ");
  System.out.println("Extracted part is =>" + targetStr.substring(-1));
}
}

The explanation of the above code block:

  • First, define a String “targetStr” containing random data.
  • Next, apply the “substring()” method on this “targetStr” string and pass a “valid” starting index value. The result returns a new substring consisting of all characters from that index number.
  • Then, again apply the “substring()” method and pass the index value of “0”. This returns an entire String as a result because “0” is the first index number.
  • Now, use a “length()” method on the “targetStr” to retrieve the length or maximum index number of “targetStr”. Now, pass the returned result in a “substring()” method and it will display nothing or empty String as a result.
  • Moreover, pass the valid index values into the “substring()” method to remove the starting character from the string.
  • Lastly, use the java “substring()” method and pass the “negative” value as the index number can not be negative. The exception of “StringIndexOutOfBoundsException” raises.

Output:

Variant 2: Public String substring(int startingPoint, int endingPoint)

This variant of a “substring()” method allows the user to set the ending point till the extraction needs to be done. The ending point is not included in the String opposite to the starting point, the values of both index points are separated by a comma “,” symbol:

public class Substring {
//defining the main method
public static void main(String[] args) {
  String targetStr = "Implementation of substring Method";
//first scenario
  System.out.println("Passing Valid Starting and Ending Index Number: ");
  System.out.println("Extracted part =>" + targetStr.substring(18, 27));

//second scenario
  System.out.println("\nPassing '0' and String Length as Index Numbers: ");
  System.out.println("Extracted part =>" + targetStr.substring(0, targetStr.length()));

//third scenario
  System.out.println("\nPassing both Starting and Ending Index Number Same: ");
  System.out.println("Extracted part =>" + targetStr.substring(23,23));

//fourth scenario
  System.out.println("\nRemoval of Ending character or word of the String: ");
  System.out.println(targetStr.substring(0, targetStr.length()-1));

//fifth scenario
  System.out.println("\nPassing invalid(Ending Index is Less than the Starting Index) Value: ");
  System.out.println(targetStr.substring(28, 13));
}
}

In the above code snippet:

  • Apply the “substring()” method over the same “targetStr” String to perform multiple case scenarios.
  • In the first scenario, insert the valid starting and ending index points to extract a specific word from the entire String.
  • In the second scenario, the starting point is set to “0” and the ending point to the last index of String. This extracts the entire provided length.
  • In the third scenario, both starting and ending points are set simultaneously. This will not display anything on the console.
  • The fourth scenario performs the removal of characters from the end position. By setting the first argument to zero. Then, subtracting the number of removed elements from the total String length and inserting it as the second argument.
  • In the fifth scenario, the ending point is set greater than the starting point which violates the rules and generates an “Out of Bound” exception.

Output

Application 1: Extract a Word From String After Every Specific Token 

In the below Java program words of the targeted String are extracted whenever the specified “,” token appears. You can modify the below code to extract the words whenever, a random token, character, or word appears as per requirements:

public class Substring {
public static void main(String[] args) {
  String targetStr = "Implementation,of,substring,Method";

  for(int startIndex = 0; startIndex < targetStr.length() ; ) {
  int commaIndex = targetStr.indexOf(',', startIndex);
  if(commaIndex == -1) {
    commaIndex = targetStr.length();
  }
  String stringWords = targetStr.substring(startIndex, commaIndex);
  System.out.println("String Word => " + stringWords);
  startIndex = commaIndex  + 1;
  }
}
}

In the above code block:

  • First, define a String “targetStr” containing random data. Next, use the “for” loop that iterates till the length of a “targetStr” String. Leave its increment part empty, it is assigned later.
  • Now, retrieve the index number of “,” inside the String and store it in a “commaIndex” variable. Also, utilize the “if” condition that stores the ending/last index of a String inside the “commaIndex” variable if its value is “-1”.
  • Then, pass the iteration variable(starting point of a String), and the “commaIndex” storing the index of our token “,” into the “substring()” method.
  • Store and print the result on the console along with it increments the value of “commaIndex” to a factor of “1”. Assign this modified value of “commaIndex” to the “startIndex” iteration variable.

Output

Application 2: Extracting Values From an Array According to Prefix and Suffix

In this example, the values are selected and filtered according to their prefix and suffix using the “substring()” method. Let’s proceed towards the code implementation:

public class Substring {
public static void main(String[] args) {
  String namesArray[] = {
  "Hart Atonal Katz", "Elrod Barlowe Katz", "Hart Afify Katz", "Whitlock Afify", "Hart Caddel Katz", "Atonal Banasiewicz Afify"
  };

//Specifying custom suffix and prefix
  String prefix = "Hart";
  String suffix = "Katz";
  int sufSize = suffix.length();
  int preSize = prefix.length();

  int size = namesArray.length;
//Searching names having the same length of suffix and prefix
  for(int j = 0; j < size; j++)
  {
  int len = namesArray[j].length();
  String subStr = namesArray[j].substring(len - sufSize);
  String subString = namesArray[j].substring(0, preSize);

//Checking if the same length word matches with suffix and prefix
  if(subString.equals(prefix))
  {
    if(subStr.equals(suffix)) {
    System.out.println(namesArray[j]);
    }
  }
  }
}
}

The above code works like this:

  • First, create an array “namesArray” containing random elements. Then, create a couple of variables containing the values for prefixes and suffixes. 
  • Also, create three more variables containing the size for the stored values and the original array “namesArray”.
  • Now, iterate the “for” loop till the size of the original array, and inside it utilizes the “substring()” method.
  • This method extracts the starting and ending word having a character count equal to the size of the stored prefix and suffix length.
  • Then, store the extracted sub-strings in separate “subStr” and “subString” variables. Now, we use the nested “if” statement and “equals()” method to check if the extracted word is equal to the one we stored in the “suffix” and “prefix” variables or not.
  • In case of yes, print that Array element on the console.

Output

Conclusion

In Java, use the “substring()” method to extract a part of the entire String according to the residing character’s index numbers. The user can either provide only the starting index or also the ending index as per requirements. Moreover, the “out of bound” exception arises whenever the user tries to enter a “negative” value as an index. Or if the ending index is less than the starting index. This guide has explained the usage of a “substring()” method in Java.