Please note, this is a STATIC archive of website www.simplilearn.com from 27 Mar 2023, cach3.com does not collect or store any user information, there is no "phishing" involved.

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." Java is one of the most common languages used by web developers around the world. 

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

Learn from the Best in the Industry!

Caltech PGP Full Stack DevelopmentExplore Program
Learn from the Best in the Industry!

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

Become a Skilled Web Developer in Just 9 Months!

Caltech PGP Full Stack DevelopmentExplore Program
Become a Skilled Web Developer in Just 9 Months!

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

Learn 15+ In-Demand Tools and Skills!

Automation Testing Masters ProgramExplore Program
Learn 15+ In-Demand Tools and Skills!

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

Basics to Advanced - Learn It All!

Caltech PGP Full Stack DevelopmentExplore Program
Basics to Advanced - Learn It All!

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. 

And if you wish to master Java and other Full Stack core topics, then check out Simplilearn's Post Graduate Program In Full Stack Web Development. This course is perfect for anyone who is looking to get started in the world of software.

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.