java.lang.String subSequence(int beginIndex,int endIndex)

Description :

This java tutorial shows how to use the subSequence(int beginIndex,int endIndex) method of String class of java.lang package. This method returns a CharacterSequence which is the result of splitting the String from beginIndex to endIndex. This is the same as the method substring(int beginIndex,int endIndex) however this method returns a String while the subSequence() method returns a CharacterSequence.

Method Syntax :

public CharSequence subSequence(int beginIndex,int endIndex)

Parameter Input :

DataType Parameter Description
int beginIndex The index which we start getting the character sequence
int endIndex The end index to which we get the character sequence on the String

Method Returns :

The method subSequence(int beginIndex, int endIndex) returns a CharSequence object type which is a substring of the parent String.

Compatibility Version :

Requires Java 1.4 and up

Exception :


The IndexOutOfBoundsException will be thrown if the following condition has been met:

  • starIndex and endIndex is negative
  • startIndex is greater than the endIndex
  • endIndex is is greater than the String length

Discussion :

The method subSequence works the same way as with substring() method of String class. The only difference is that this method returns CharSequence data type instead of String. This generally helpful if our business requirements require a CharSequence data type. The index starts at 0 and the lastIndex maximum value is String length. If the start and end index is equal with each other, the result would be an empty String because this scenario leaves the subsequence to occupy 0 length.

Java Code Example :

This example java code shows the usage the method subSequence() of String class. Basically this code just take a sample string and use the subsequence to get a portion of the string. The return type is of CharSequence data type and we output the same on the console using System.out.println(String) method.


 * Example java source code on String subSequence() method

public class StringSubSequenceDemo {

	public static void main(String[] args) {
		String strExample = "this is an example string";
		CharSequence cs = strExample.subSequence(2, 5);



Sample Output :

Running the subSequence(int beginIndex,int endIndex) method example source code of String class will give you the following output

java string subsequence method example

java string subsequence method example

Exception Scenario :

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 53
	at java.lang.String.substring(Unknown Source)
	at java.lang.String.subSequence(Unknown Source)

Similar Method :

  • substring(int beginIndex,int endIndex)

Suggested Reading List :

References :