Substring means part of a string. Many times in an application, we get a long string and we need to extract some portion from it.
java.lang.String class provides substring method for this purpose.

There are two overloaded variants of substring method as explained below.

1. substring(int beginIndex): Accepts an integer as argument and returns the string starting from this index till the end of string. Example,
"".substring(8) will return “com”.
Remember that string indexing starts at 0.
That is, first character will be at index 0, second at 1 and so on. Thus, the character at 8th index in above example will be ‘c’.

2. substring(int beginIndex, int endIndex): This method is used when you want a portion of string between two indexes.
Returned string will have index between beginIndex and (endIndex – 1).
"".substring(0, 7) will return “codippa”, which is the string between indexes 0 and 6.

Each of these methods should be called on a string and returns a new string which is the substring as per the provided index(es).
Original string remains unchanged.

Substring Example: First method
Following is an example program that demonstrates the use of single argument substring method.

public class SubstringDemo {
   public static void main(String[] args) {
      String str = "";
      // get string after 8th character
      String subStr = str.substring(8);

It will print


Substring example: Second method
Below program shows an example of how to get substring between two index positions.

public class SubstringDemo {
   public static void main(String[] args) {
      String str = "Learning substring";
      // get string between 5th and 11th character
      String subStr = str.substring(4, 12);

Above program will output

ning sub

substring is a method of string manipulation in java.
But remember that the original string does not change by calling this method because java.lang.String class is immutable.

Learn how to create your own immutable class here.

If you liked this post, then hit the clap button below as a token of appreciation.


Leave a Reply