A substring is a subset or part of another string, or it is a contiguous sequence of characters within a string. For example, "Substring" is a substring of "Substring in Java." 

What is a Substring in Java?

Substring in Java is a commonly used method of java.lang.String class that is used to create smaller strings from the bigger one. As strings are immutable in Java, the original string remains as it is, and the method returns a new string. 

Syntax:

string.substring(int startIndex, int endIndex)

Note: Here, the endIndex is exclusive, but the startindex is inclusive, and the string is an object of the String class. We will see the use more in detail below. 

The method produces an IndexOutofBoundsException if:

  1. endIndex is less than startIndex
  2. endIndex/StartIndex is greater than the string's length
  3. endIndex/StartIndex is negative

Full Stack Java Developer Course

In Partnership with HIRIST and HackerEarthEXPLORE COURSE
Full Stack Java Developer Course

Methods to Get a Substring

Substring in Java can be obtained from a given string object using one of the two variants:

1. Public String substring(int startIndex)

This method gives a new String object that includes the given string's substring from a specified inclusive startIndex. 

Syntax: public String substring(int startIndex)

Parameters: startIndex- the starting index (inclusive)

Returns: Specified substring 

Example: 

Code: public class TestSubstring { 

    public static void main(String args[]) 

    {

      // Initializing the String 

        String Str = new String("Substring in Java Tutorial"); 

        // using substring() to extract substring 

        //  should return: in Java Tutorial

        System.out.print("The extracted substring is : "); 

        System.out.println(Str.substring(10)); 

    } }

Output:

startIndex

2. Public String substring(int startIndex, int endIndex):

This method is used to return a new String object that includes a substring of the given string with their indexes lying between startIndex and endIndex. If the second argument is given, the substring begins with the element at the startIndex to endIndex -1. 

Syntax : public String substring(int startIndex, int endIndex)

Parameters: startIndex:  the starting index, inclusive

endIndex:  the ending index, exclusive.

Return Value: Specified substring.

Example:

Code: public class TestSubstring { 

    public static void main(String args[]) 

    { 

     // Initializing the String 

        String Str = new String("Substring in Java Tutorial"); 

        // using substring() to extract substring 

        // should return Java

        System.out.print("The extracted substring  is : "); 

        System.out.println(Str.substring(13, 17)); 

    } 

}

Output:

endIndex

FREE Java Certification Training

Learn A-Z of Java like never beforeEnroll Now
FREE Java Certification Training

Also Read: The Best Java Programs for Beginners and Experienced Programmers to Practice and Upskill

Use and Applications of Substring

1. The substring in Java method is used in many applications, including suffix and prefix extraction. For instance, if you want to extract the last name from a given name or extract the digits after the decimal point from a string containing digits both before and after the point. Here is the demonstration: 

Code:

// Java code to demonstrate the application of substring method 

public class TestSubstring { 

    public static void main(String args[]) 

    {

        // Initializing the String 

        String Str = new String("Rs 1500"); 

        // Printing the original string 

        System.out.print("The original string  is : "); 

        System.out.println(Str); 

        // using substring method to extract substring 

        // returns 1500 

        System.out.print("The extracted substring  is : "); 

        System.out.println(Str.substring(3)); 

    } 

}

Output:

suffixandprefix%20

2. Check palindrome- We can use the substring in Java method to check if the given string is palindrome or not, i.e. if its read the same way from both ends. Here’s the demonstration: 

Code- public class TestSubstring {

public static void main(String[] args) {

System.out.println(checkPalindrome("adeda"));

System.out.println(checkPalindrome("ABba"));

System.out.println(checkPalindrome("1234321"));

System.out.println(checkPalindrome("AAAA"));

}

private static boolean checkPalindrome(String s) {

if (s == null)

return false;

if (s.length() <= 1) {

return true;

}

String first = s.substring(0, 1);

String last = s.substring(s.length() - 1);

if (!first.equals(last))

return false;

else

return checkPalindrome(s.substring(1, s.length() - 1));

}

}

Output-

palindrome

Full Stack Web Developer Course

To become an expert in MEAN StackView Course
Full Stack Web Developer Course

3. To get all the substrings of a string. Here is the code:

public class TestSubstring {

// Function to print all substrings of a string

public static void SubString(String s, int n)

{

for (int i = 0; i < n; i++)

for (int j = i+1; j <= n; j++)

System.out.println(s.substring(i, j));

}

public static void main(String[] args)

{

String s = "defg";

SubString(s, s.length());

}

}

Output-

Explain the variants of the substring() method.

The two variants of the substring() method are:

  • String substring()
  • String substring(startIndex, endIndex)

Here is how two variants of the substring in the Java method can be used:

1. To get the first m and last n characters of a string. 

Code:

public class TestSubstring {

public static void main(String[] args) {

String str = "Substring in Java Tutorial";

System.out.println("Last 8 char String: " + str.substring(str.length() - 8));

System.out.println("First 9 char String: " + str.substring(0, 9));

System.out.println("Topic name: " + str.substring(13, 26));

}

}

Output:

firstlast

New Course: Full Stack Development for Beginners

Learn Git Command, Angular, NodeJS, Maven & MoreEnroll Now
New Course: Full Stack Development for Beginners

2. It is interesting to note that substring in the Java method will return an empty string if the string's length is passed as a parameter or if the same index is given as startIndex and endIndex. Here is an example:

Code: public class TestSubstring { 

public static void main(String[] args) { 

String quote = "Substring in Java Tutorial";

String substr = quote.substring(quote.length()); System.out.println(substr.isEmpty()); 

//if begin = end 

String sub = quote.substring(3,3); 

System.out.println(sub.isEmpty());

}}

Output:

emptystring

3. Deleting the first character : Strings in Java start at index 0, i.e., the first character is 0 indexed. If you need to remove the first character, use substring(1). This returns the substring without the initial character, which equals deleting the first character. 

Code: public class TestSubstring { 

public static void main(String[] args) { 

String quote = "Substring in Java Tutorial";

String substr = quote.substring(1); 

System.out.println(substr); 

}}

Output:

Deleting

Note: If the endIndex is not specified then the substring in Java method returns all characters from startIndex. 

We offer complete Job Guarantee and money-back if you don't secure a job within 6 months of graduation. Get interview ready with intense and comprehensive career mentoring sessions in our Full Stack Java Developer Program. Enroll TODAY!

And if you wish to master Java, you must enroll in our Java Certification Training Program and ace your web application development career, starting today! If you have any doubts or questions, you can drop a comment below, and our experts would be happy to answer them.

About the Author

Ravikiran A SRavikiran A S

Ravikiran A S works with Simplilearn as a Research Analyst. He an enthusiastic geek always in the hunt to learn the latest technologies. He is proficient with Java Programming Language, Big Data, and powerful Big Data Frameworks like Apache Hadoop and Apache Spark.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.
  • *According to Simplilearn survey conducted and subject to terms & conditions with Ernst & Young LLP (EY) as Process Advisors