Java StringBuilder substring() Method Example

Java StringBuilder provides two overloaded versions of the 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 StringBuilder lastIndexOf() Method Example

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

Reference


Comments