Java StringBuffer substring() Example

There are two overloaded versions of the Java StringBuffer class substring() method:
  1. String substring(int start) - Returns a new String that contains a subsequence of characters currently contained in this character sequence.
  2. String substring(int start, int end) - Returns a new String that contains a subsequence of characters currently contained in this sequence.

Java StringBuffer substring() Example

Example: This example demonstrates the usage of both overloaded versions of substring() methods.
public class SubStringExample {
    public static void main(String[] args) {
        StringBuffer buffer = new StringBuffer("javaguides");
  
        // substring from start to end
        String subStr = buffer.substring(0, buffer.length());
        System.out.println("substring from 0 to length of the string : " + subStr);
  
        // print java
        System.out.println(buffer.substring(0, 4));
  
        // print guides
        System.out.println(buffer.substring(4, buffer.length()));
    }
}
Output:
substring from 0 to length of the string : javaguides
java
guides

Reference




Comments