Java.lang.String.subSequence() Method

Advertisements


Description

The java.lang.String.subSequence() method returns a new character sequence that is a subsequence of this sequence.

Declaration

Following is the declaration for java.lang.String.subSequence() method

public CharSequence subSequence(int beginIndex, int endIndex)

Parameters

  • beginIndex -- This is the value of begin index, inclusive.

  • endIndex -- This is the value of the end index, exclusive.

Return Value

This method returns the specified subsequence.

Exception

  • IndexOutOfBoundsException -- if beginIndex or endIndex are negative, if endIndex is greater than length(), or if beginIndex is greater than startIndex.

Example

The following example shows the usage of java.lang.String.subSequence() method.

package com.tutorialspoint;

import java.lang.*;

public class StringDemo {

  public static void main(String[] args) {
  
    String str = "Tutorials Point!";

    System.out.println("string = " + str);
    
    // returns the specified subsequence from index 2 to 9
    System.out.println("string subsequence = " + str.subSequence(2,9));
  }
}

Let us compile and run the above program, this will produce the following result:

string = Tutorials Point!
string subsequence = torials



Advertisements
Advertisements