Java.lang.StringBuilder.substring() Method



Description

The java.lang.StringBuilder.substring(int start, int end) method returns a new String that contains a subsequence of characters currently contained in this sequence. The substring begins at the specified start and extends to the character at index end - 1.

Declaration

Following is the declaration for java.lang.StringBuilder.substring() method

public String substring(int start, int end)

Parameters

  • start − This is the beginning index, inclusive.

  • end − This is the ending index, exclusive.

Return Value

This method returns the new string.

Exception

StringIndexOutOfBoundsException − if start or end are negative or greater than length(), or start is greater than end.

Example

The following example shows the usage of java.lang.StringBuilder.substring() method.

package com.tutorialspoint;

import java.lang.*;

public class StringBuilderDemo {

   public static void main(String[] args) {
  
      StringBuilder str = new StringBuilder("admin");
      System.out.println("string = " + str);

      // prints substring from index 3
      System.out.println("substring is = " + str.substring(3));

      /* prints substring from index 1 to 4 excluding character
         at 4th index */
      System.out.println("substring is = " + str.substring(1, 4));
   }
}

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

string = admin
substring is = in
substring is = dmi
java_lang_stringbuilder.htm
Advertisements