Java Tutorial Java Advanced Java References

Java String - substring() Method



The Java substring() method returns a string that is a substring of the given string. This method has two versions.

In first version, the substring begins with the character at the specified index and extends to the end of this string.

In second version, the 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)	
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

In first version - throws IndexOutOfBoundsException, if beginIndex is negative or larger than the length of this String object. In second version - 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.

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

    //version 1 - returns string that starts from specified
    //index and extends to the end of the string.
    System.out.println(MyString.substring(6));
    
    //version 2 - returns string that starts 
    //and ends at specified indices
    System.out.println(MyString.substring(0, 5)); 
  }
}

The output of the above code will be:

World
Hello

❮ Java String Methods