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

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

How Does the Method of Substring() Operate?

Let's look at an example to see how the substring() method functions. Assume we have a string "Hello, World!" and wish to extract the substring "World". To do this, we may utilize the substring() technique as seen below:

String str = "Hello, World!";
String substr = str.substring(7, 12);

The Java substring(begIndex, endIndex) method extracts a portion of a given string. It returns a new string containing the original string's characters from the begIndex (inclusive) up to the endIndex (exclusive).

String str = "Hello World";
String substr = str.substring(6, 11);
System.out.println(substr); // Output: "World"

In this example, the substring() method is called on the str string with parameters 6 and 11. This means that the new substring will start at index 6 (which is the letter 'W' in "World") and end at index 11 (which is the last letter 'd' in "World"). The resulting substring is then assigned to the substrate variable and printed to the console.

Some Exception Handling and Corner Cases Programs in Java

Here's an example program that uses the substring() method in Java, including some exception handling and corner cases:

public class SubstringExample {
public static void main(String[] args) {
    String str = "Hello World";

    // Extract a substring from index 6 to the end of the string
    String substr1 = str.substring(6);
    System.out.println(substr1); // Output: "World"

    // Extract a substring from index 0 to index 5 (exclusive)
    String substr2 = str.substring(0, 5);
    System.out.println(substr2); // Output: "Hello"

    // Try to extract a substring with an end index greater than the length of the string
    try {
        String substr3 = str.substring(6, 20);
        System.out.println(substr3);
    } catch (StringIndexOutOfBoundsException e) {
        System.out.println("Exception caught: " + e.getMessage());
    }
    // Output: "Exception caught: String index out of range: -9"

    // Try to extract an empty substring
    String substr4 = str.substring(5, 5);
    System.out.println(substr4); // Output: ""
}
}

In this example program, we first define a string str with the "Hello World" value. We then use the substring() method to extract two substrings: substr1 from index 6 to the end of the string and substr2 from index 0 to index 5 (exclusive). Finally, these substrings are printed on the console.

We then attempt to extract a substring with an end index of 20, which is greater than the length of the string. This will cause a StringIndexOutOfBoundsException to be thrown, so we catch the exception and print a message to the console.

Finally, we attempt to extract an empty substring by passing the same index value for begIndex and endIndex. This will result in an empty string being returned, which is printed to the console.

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

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

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

Internal Implementation of Substring Function in Java

The substring() function in Java is used to extract a part of a given string. The function returns a new string containing a portion of the original string, starting from the specified index to the end or to the specified end index. In this article, we'll explore the internal implementation of Java's substring() function.

Syntax of Substring() Function:

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

The substring() function takes two parameters: startIndex and endIndex. The startIndex parameter specifies the starting index of the substring. The endIndex parameter is optional, and specifies the ending index of the substring. If endIndex is not specified, the substring will start from the startIndex index and continue to the end of the original string.

Internal Implementation of Substring Function

The substring() function is implemented in the String class in Java. When the substring() function is called on a string object, the Java Virtual Machine (JVM) creates a new string object and copies the required characters from the original string object to the new string object.

Let's take a closer look at the implementation of the substring() function:

public String substring(int startIndex) {
if (startIndex < 0 || startIndex > value.length) {
    throw new StringIndexOutOfBoundsException(startIndex);
}
return ((startIndex == 0) ? this : new String(value, startIndex, value.length - startIndex));
}

public String substring(int startIndex, int endIndex) {
if (startIndex < 0 || endIndex > value.length || startIndex > endIndex) {
    throw new StringIndexOutOfBoundsException();
}
return ((startIndex == 0 && endIndex == value.length) ? this
        : new String(value, startIndex, endIndex - startIndex));
}

In the first implementation, the function takes only one parameter, startIndex. The function first checks whether the startIndex is valid. If the startIndex is less than 0 or greater than the length of the original string, a StringIndexOutOfBoundsException is thrown. If the startIndex is 0, the function returns the original string object. If the startIndex is valid, the function creates a new string object with the specified range of characters from the original string object.

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

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

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

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

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. 

In Java, substrings are portions of a string extracted by specifying start and end indices. This functionality is crucial for efficient text manipulation and data extraction. Understanding substrings is essential for effective string handling in Java applications. Enroll in a Java Course to master substring operations and enhance your programming skills.

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.

Our Software Development Courses Duration And Fees

Software Development Course typically range from a few weeks to several months, with fees varying based on program and institution.

Program NameDurationFees
Caltech Coding Bootcamp

Cohort Starts: 16 Dec, 2024

6 Months$ 8,000
Automation Test Engineer Masters Program

Cohort Starts: 27 Nov, 2024

8 months$ 1,499
Full Stack Java Developer Masters Program

Cohort Starts: 18 Dec, 2024

7 months$ 1,449
Full Stack (MERN Stack) Developer Masters Program

Cohort Starts: 8 Jan, 2025

6 Months$ 1,449