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 character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex.

Syntax

public String substring(int beginIndex, int endIndex)

Parameters

beginIndex specify the begin index (inclusive).
endIndex specify the end index (exclusive).

Return Value

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

Exception

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

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 
    //and ends at specified indices
    System.out.println(MyString.substring(0, 5)); 
  }
}

The output of the above code will be:

Hello

❮ Java.lang - String