Java.lang Package Classes

Java - String substring() Method



The Java string substring() method returns a string that is a substring of the given string. This method has two versions. The returned substring begins with the character at the specified index and extends to the end of this string.

Syntax

public String substring(int beginIndex)	

Parameters

beginIndex specify the begin index (inclusive).

Return Value

Returns a string that is a substring of the given string.

Exception

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

Example:

In the example below, substring() method returns a string that is a substring of the given string called MyString.

import java.lang.*;

public class MyClass {
  public static void main(String[] args) {
    String MyString = "Hello World";

    //returns string that starts from specified
    //index and extends to the end of the string.
    System.out.println(MyString.substring(6));
  }
}

The output of the above code will be:

World

❮ Java.lang - String