Substring in Java | Methods, Example

Substring in Java is a subset of the main string specified by start and end indices. We can extract substrings by using substring() method. Consider the following example.

String str = "Hello, World";
String sub = str.substring(0, 5); // sub is "Hello".

In this example, substring() method obtains a substring from a string that consists of the first five characters taken from the string str. Look at the below figure to understand better.

Java substring

As you can see in the above figure, the count characters begin with 0, not 1. The character at the end Index (i.e. at 5 position) is not part of the substring. Therefore, sub is “Hello”.

Let’s understand how to extract the substring “World” from a string. From the above figure, W has position number 7. The last character that we do not want, is position number 12.

So, the appropriate substring command is:

String sub2 = str.substring(7, 12);

If we remove the end position when invoking the substring method, all characters from the beginning position to the end of the string are copied.

For example:

String sub3 = str.substring(7); // Copies all characters from position 7 to the end of the string.

Therefore, sub3 is “World”.

Substring Methods in Java


String class provides two forms of substring methods in Java. They are as follows:

1. public String substring(int startIndex): This method returns a new string that is a substring of this string. Here, startIndex represents the index at which the substring begins with a character. The substring starts at startIndex and executes until the end of the string. For example:

String s = "India";
s.substring(3);

Here, startIndex is 3. So, it will return characters starting 3rd character till the end of s. Thus, the single-argument (i.e. startIndex) extracts a substring from the specified starting index to the end of the string.

Note that if the startIndex is larger than the length of string or less than zero, the substring() method will throw an exception named IndexOutOfBoundsException.


2. public String substring(int startIndex, int endIndex): This method returns a new string of all the characters from starting index up to ending index but not including, the ending index. For example:

String s = "India"; 
s.substring(1,3);

It will return characters of s starting from 1st to 2nd position. Thus, the double-argument (i.e. startIndex and endIndex) extracts the substring of the given string from the specified startIndex to endIndex.

The substring() method will throw IndexOutOfBoundsException exception if:

  • the startIndex is less than zero or greater than endIndex
  • endIndex is greater than length of string.

Note that we cannot use negative indices with the substring() method in Java. You should provide valid, non-negative indices.

Substring Example Program


Let’s take a simple example program based on the above Java substring methods.

Program code 1:

package stringPrograms; 
public class SubstringTest { 
public static void main(String[] args) 
{ 
   String s1 = "HelloJava"; 
   String s2 = s1.substring(5); 
   System.out.println(s2); 
  
   String s3 = s1.substring(3, 9); // Java 
   System.out.println(s3); // loJava 
 } 
}
Output: 
       Java 
       loJava

Explanation:

1. s1.substring(3,9); will return characters of s starting from 3rd to 8th position and it will be stored in the heap area.

2. s1.substring(5); will return characters starting from 5th character till the end of s1.

Look at the memory concept in the below diagram.
Substring in Java
Key point:

1. Index starts from 0 to (n-1).


Consider the below program and answer the following questions:

1. What will be the output of the following program?

2. How many string objects will create in the heap and string constant pool?

Program code 2:

package stringPrograms; 
public class SubstringTest { 
public static void main(String[] args) 
{ 
   String s = new String("SachinTendulkar");
   s.substring(5);
   System.out.println(s); 

   String s2 = s.substring(6, 15); 
   System.out.println(s2); 

   String s3 = s2.substring(3); 
   System.out.println(s3); 
 } 
}
Output: 
       SachinTendulkar 
       Tendulkar 
       dulkar

Look at the memory concept first.
Java Substring
Explanation:

1. When JVM will execute the line String s = new String(“SachinTendulkar”);, it will create an object in the heap area and store content “SachinTendulkar” in it. The reference variable ‘s’ will be pointed to that object “SachinTendulkar” by JVM as shown in the figure.

We know that for every string literal, JVM also creates one copy of the object in the string constant pool for future purposes and store content in it.

2. When line s.substring(5); will be executed, substring() will return a new string “nTendulkar” starting from 5th position till the end that is the substring of the original string.

JVM will create a new object in the heap area and store content “nTendulkar” in it. Since we are not pointing any reference variable to it. Therefore, the garbage collector will remove it from memory.

Since ‘s’ is still pointing to “SachinTendulkar”. Therefore, the output will be “SachinTendulakar”.


3. During the execution of line String s2 = s.substring(6, 15);, the substring method will create a new string of all the characters from 6th to 15th position of the main string.

JVM will store content “Tendulkar” by creating an object in the heap area. A reference variable ‘s2’ will point to this object by JVM and the output will be “Tendulkar”.


4. Similarly, during the execution of line String s3 = s2.substring(3);, an object with content “Tendulkar” will be called using the reference ‘s2’ by JVM, and substring() method will create a new string “dulkar” starting from 3rd position till the end.

This new string will be stored in the heap area by creating a new object and ‘s3’ will refer to this object. Therefore, the output is “dulkar”.

As you can see in the above figure, a total of 5 objects have been created, one in the string constant pool and four in the heap area. So, the answer is 5.

Extracting Substring using String.split() Method


In Java, we can also use the split() method of String class to extract substrings from a given string object based on a specified delimiter. This method allows us to split a string into an array of substrings. Let’s take an example in which we will use a regular expression as a delimiter with String.split() method to extract substrings.

Program code 3:

package stringPrograms;
import java.util.Arrays;
public class StringSplitExample {
public static void main(String[] args) 
{
   String text = "My name is Deepak. I am 26 years old. I live in Dhanbad.";

// Split strings by the delimiter passed as an argument.
   String[] str = text.split("\\.");
	        
// Display the extracted strings.
   System.out.println(Arrays.toString(str));
  }
}
Output:
       [My name is Deepak,  I am 26 years old,  I live in Dhanbad]

In this example program, we have used the split() method of string class. This method accepts a regular expression (\\.) as an argument that splits the text string into an array of substrings. The text string will split into an array of substrings separated with commas wherever the dot (.) will encounter in the sentences. The regular expression (\\.) effectively represents a period as a delimiter.

⇐ PrevNext ⇒

Please share your love