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:
- endIndex is less than startIndex
- endIndex/StartIndex is greater than the string's length
- endIndex/StartIndex is negative
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!"; |
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"; |
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 { |
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:
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:
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) { |
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: |
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:
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:

Also Read: 40+ Resources to Help You Learn Java Online
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:
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:
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:
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.