Java.lang.String.substring() Method

Advertisements


Description

The java.lang.String.substring(int beginIndex) method returns a new string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string.

Declaration

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

public String substring(int beginIndex)

Parameters

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

Return Value

This method returns the specified substring.

Exception

  • IndexOutOfBoundsException -- if beginIndex is negative or larger than the length of this String object.

Example

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
    substr = str.substring(7);
    System.out.println("substring = " + substr);

    // prints the substring after index 0 i.e whole string gets printed
    substr = str.substring(0);
    System.out.println("substring = " + substr);
  }
}

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

substring = tutorials point
substring = This is tutorials point



Advertisements
Advertisements