Join our newsletter for the latest updates.

Java String substring()

The Java String substring() method extracts a substring from the string and returns it.

The syntax of the substring() method is:

string.substring(int startIndex, int endIndex)

Here, string is an object of the String class.


substring() Parameters

The substring() method takes two parameters.

  • startIndex - the begining index
  • endIndex (optional) - the ending index

substring() Return Value

The substring() method returns a substring from the given string.

  • The substring beings with the character at the startIndex and extends to the character at index endIndex - 1.
  • If the endIndex is not passed, the substring beings with the character at the specified index and extends to the end of the string.
Working of Java String substring() method
Working of Java String substring() method

Note: You will get an error if,

  • startIndex/endIndex is negative or greater than string's length
  • startIndex is greater than endIndex


Example 1: Java substring() Without End Index

class Main {
    public static void main(String[] args) {
        String str1 = "program";

        // from the first character to end
        System.out.println(str1.substring(0));  // program

        // from the 4th character to end
        System.out.println(str1.substring(3));  // gram
    }
}

Example 2: Java substring() With End Index

class Main {
    public static void main(String[] args) {
        String str1 = "program";

        // from 1st to the 7th  character
        System.out.println(str1.substring(0, 7));  // program

        // from 1st to the 5th  character
        System.out.println(str1.substring(0, 5));  // progr

        // from 4th to the 5th character
        System.out.println(str1.substring(3, 5));  // gr
    }
}

If you need to find the index of the first occurrence of the specified substring from a given string, use the Java String indexOf().