Home » Java programming language

Java StringBuilder subSequence() method with example

StringBuilder Class subSequence() method: Here, we are going to learn about the subSequence() method of StringBuilder Class with its syntax and example.
Submitted by Preeti Jain, on December 22, 2019

StringBuilder Class subSequence() method

  • subSequence() method is available in java.lang package.
  • subSequence() method is used to return the new set of a character sequence that is a subset of this sequence.
  • subSequence() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
  • subSequence() method may throw an exception at the time of character sequence.
    IndexOutOfBoundsException – This exception may throw when end_seq > length or when st_seq > end_seq or when st_seq or end_seq are less than 0.

Syntax:

    public CharSequence subSequence(int st_seq, int end_seq);

Parameter(s):

  • int st_seq – represents the beginning index of this character sequence.
  • int end_seq – represents the ending index of this character sequence.

Return value:

The return type of this method is CharSequence, it returns the given subsequence of this character sequence.

Example:

// Java program to demonstrate the example 
// of subSequence(int st_seq, int end_seq)
// method of StringBuilder 

public class SubSequence {
    public static void main(String[] args) {
        // Creating an StringBuilder object
        StringBuilder st_b = new StringBuilder("Java World ");

        // Display st_b object
        System.out.println("st_b = " + st_b);

        // By using subSequence() method is to return the sequence 
        // from the given index 0 to index 3 (but it does not include
        // last index i.e. 4)
        CharSequence cs = st_b.subSequence(0, 4);

        System.out.println("st_b.subSequence(0,4) = " + cs);
    }
}

Output

st_b = Java World 
st_b.subSequence(0,4) = Java



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.