String subSequence in Java

The Java String subSequence Method is used to return a new character sequence that is a subsequence of the user-specified string. In this article, we will show how to use subSequence with an example.

Syntax

The syntax of the Java string subSequence is as shown below.

The following method will accept the integer value that is the starting index position (Starting_index), where the extraction will start as the first parameter. And the last index position (End_index), where the character sequence will end as the second argument.

The Java String subSequence method will return the character sequence starting from the Starting_index up to End_index but not included.

public CharSequence subSequence(int Startig_index, int End_index); // It will return Character Sequence 

//In order to use in program
String_Object.subSequence(int Startig_index, int End_Index)
  • String_Object: Please specify the valid Object.
  • Starting_Index: Please specify the starting index position. It is the index position where the extraction of the character sequence will start.
  • End_Index: Please specify the ending index position. The subSequence function will return up to this index position, but it will not include the character at this position (End_index).

Example for String subSequence in Java

The subSequence method extracts the part of a string and returns a new one. This program will help to understand the string.subSequence method.

package StringFunctions;

public class SubSequenceMethod {
	public static void main(String[] args) {
		String str = "Tutorials on Java Programming";
		String str1 = "We are abc working at abc company";
		
		System.out.println("subSequence of str = " + str.subSequence(0, 10));
		System.out.println("subSequence of str1 = " + str1.subSequence(0, 12));
		
		System.out.println("subSequence of str = " + str.subSequence(5, 10));
		System.out.println("subSequence of str1 = " + str1.subSequence(5, 12));
		
		System.out.println("subSequence of str = " + str.subSequence(6, str.length()));
		System.out.println("subSequence of str1 = " + str1.subSequence(5, str1.length()));
	}
}
String subSequence in Java 1

It will call the public CharSequence subSequence (int Starting_Index, int End_Index) method and return the string starting from index 0 to index position 9

System.out.println("subSequence of str = " + str.subSequence(0, 10));

This statement will call the public CharSequence subSequence (int Starting_Index, int End_Index) method. And it returns the character sequence starting from index 5 to index position 9

System.out.println("subSequence of str = " + str.subSequence(5, 10));

The last but one Method statement will return the character sequence starting from index 6 to the end of the string. Here, we used the Java length function to find the length.