String subSequence in Java

The Java String subSequence Method returns a new character sequence that is a subsequence of the user-specified string. This article will show how to use subSequence with an example.

Java subSequence Syntax

The syntax of the Java string subSequence is shown below.

The following method will accept the integer value, 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 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 will not include the character at this position (End_index).

Java String subSequence Example

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

Analysis

It will call the Java 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.