English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java flow control

Java array

Java object-oriented (I)

Java object-oriented (II)

Java object-oriented (III)

Java Exception Handling

Java List

Java Queue (queue)

Java Map collection

Java Set collection

Java input output (I/O)

Java Reader/Writer

Java other topics

Java String substring() usage and example

Java String (String) Methods

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

The syntax of substring() method is:

string.substring(int startIndex, int endIndex)

substring() parameters

The substring() method has two parameters.

  • startIndex - Start index

  • endIndex (Optional)-End index

The return value of substring()

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

  • The substring exists with the character at startIndex and extends to the index endIndex - 1of the characters.

  • If endIndex is not passed, the substring exists with the character at the specified index and extends to the end of the string.

The working of Java String substring() method

Note:If startIndex or endIndex is negative or greater than the length of the string, an error will occur. An error will also occur if startIndex is greater than endIndex.

Example1: Java substring() without ending index

class Main {
    public static void main(String[] args) {
        String str1 = "program";
        //from the first character to the end
        System.out.println(str1.substring(0));  // program
        //from the fourth character to the end
        System.out.println(str1.substring(3));  // gram
    }
}

Example2: Java substring() with ending index

class Main {
    public static void main(String[] args) {
        String str1 = "program";
        //from the first character to the seventh character
        System.out.println(str1.substring(0, 7));  // program
        //from1to5character
        System.out.println(str1.substring(0, 5));  // progr
        //from4to5character
        System.out.println(str1.substring(3, 5));  // gr
    }
}

If you need to find the index of the first occurrence of a specified substring in a given string, useJava String indexOf() Method.

Java String (String) Methods