Java.lang.String.substring() Method



The java.lang.String.substring(int beginIndex, int endIndex) method returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex.


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

public String substring(int beginIndex, int endIndex)


  • beginIndex − This is the value of beginning index, inclusive.

  • endIndex − This is the value of ending index, exclusive.

Return Value

This method returns the specified substring.


IndexOutOfBoundsException − if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex.


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

package com.tutorialspoint;

import java.lang.*;

public class StringDemo {

   public static void main(String[] args) {

      String str = "This is tutorials point";
      String substr = "";
      // prints the substring after index 7 till index 17
      substr = str.substring(7, 17);
      System.out.println("substring = " + substr);

      // prints the substring after index 0 till index 7
      substr = str.substring(0, 7);
      System.out.println("substring = " + substr);

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

substring =  tutorials
substring = This is