Substring in Java

Substring in Java represents a part of a String. Part of String could range from blank string to complete string itself.

e.g. Suppose there is a String “HelloWorld”

then possible substrings could be “H”,”ello”,”worl” ,”ellow”,”Hell” and many others. These are contiguous parts of the String.

To get substring of a String in Java, substring() method can be used. There are two variants of substring() method in Java.

Variants of substring in Java:

(1) String substring(int initialIndex);

initialIndex — Inclusive

This method will give substring from the specified initial index(inclusive) till the end of the String .
e.g.
String str = “HelloWorld”;
System.out.println(str.substring(1)); // o/p : elloWorld

(2.) String substring(int initialIndex, int endIndex);

initialIndex — Inclusive
endIndex — Exclusive

This method will give substring from the specified initial index(inclusive) till the endIndex(exclusive).
e.g.
String str = “HelloWorld”;
System.out.println(str.substring(1,6)); // o/p : elloW

Let’s take an example to illustrate this.

Example : Substring in Java
package com.masterjavatutorial;
public class TestExample {
    public static void main(String[] args) {
	String str ="HelloWorld"; 
	String substr = str.substring(1); 
	System.out.println("Substring(1) in HelloWorld="+substr); 

	String str1 ="HelloWorld"; 
	String substring = str1.substring(1, 6); 
	System.out.println("Substring(1,6) in HelloWorld="+substring); 
    }
}

Output of the above method is as below:

Substring(1) in HelloWorld=elloWorld
Substring(1,6) in HelloWorld=elloW
What if the endIndex is greater than the length of the String??

if the endIndex is greater than the length of the String, then it would throw StringIndexOutOfBoundsException as it would try to get character at indexes greater than the length of the String which does not exists. Hence, Index becomes out of bounds in this case.

package com.masterjavatutorial;
public class TestExample {
   public static void main(String[] args) {
	String str1 ="HelloWorld"; 
	String substring = str1.substring(1, 14); 
	System.out.println("Substring(1,14) in HelloWorld="+substring); 
   }
}

Output of this program is as below:

Substring(1) in HelloWorld=elloWorld
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 14
	at java.lang.String.substring(String.java:1963)
	at com.masterjavatutorial.TestExample.main(TestExample.java:9)
What if the endIndex is equal to initialIndex in Substring in Java??

if the endIndex is equal to initialIndex , then substring will return blank string whose length will be 0.

package com.masterjavatutorial;
public class TestExample {
   public static void main(String[] args) {
	String str1 ="HelloWorld"; 
	String substring = str1.substring(2, 2); 
	System.out.println("Substring(2,2) in HelloWorld="+substring.length()); 
   }
}

Output of the above program is as below:

Substring(2,2) in HelloWorld=0