Java String substring()

In this tutorial, we will learn about the Java String substring() method with the help of examples.

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

Example

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

    // extract substring from index 0 to 3
System.out.println(str1.substring(0, 4));
} } // Output: java

Syntax of substring()

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 beginning index
  • endIndex (optional) - the ending index

substring() Return Value

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

  • The substring begins with the character at the startIndex and extends to the character at index endIndex - 1.
  • If the endIndex is not passed, the substring begins 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 the end
System.out.println(str1.substring(0)); // program
// from the 4th character to the 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().

Did you find this article helpful?