The Power of Substring Function in Java
Have you ever wondered how to manipulate parts of a string in Java efficiently? The substring method is a key tool for this, enabling the extraction and processing of string segments with ease and proving indispensable in a wide array of programming scenarios.
Java is the most commonly used programming language across the world. It is an object-oriented and multi-platform programming language. In Java, collections of characters are known as Strings. Java String contains various methods which can be used to manipulate string, substring() is one such method. As the name suggests, substring is the subset or fragment of string. The substring() method extracts the substring from the given string and returns a new string as the result.
Table of Content
- Introduction to Substring Method in Java
- Different Forms of Java Substring() Method
- Various Examples of Java Substring() Method
- Some Applications of Java Substring() Method
Best-suited Java courses for you
Learn Java with these high-rated online courses
Introduction to Substring Method in Java
As discussed above, the substring() method extracts out substring from the given string and returns a completely new string. It’s syntax can be in two forms:
- String substring(int startIndex)
- String substring(int startIndex, int lastIndex)
IndexOutOfBound is the common exception seen in the substring() method. This exception occurs if:
- The value of startIndex is greater than lastIndex.
- Either the value of startIndex or lastIndex is greater than the length of the main string.
- The value of startIndex or lastIndex is negative.
Let’s see how the substring() method works. Suppose we have a string “Education is must”, & we wish to extract “Education” substring from it. In this case, Java substring() method is used.
Example
import java.util.*;public class Main { public static void main(String[] args) {// Initialize the stringString mainString = "Education is must";// substring(0,9) method extract the word EducationString extractedString = mainString.substring(0, 9);System.out.println("The substring is "+ extractedString);}}
Output
The substring is Education
As we can see in the above example, the index of character E is ‘0’, and the index of character n is ‘8’. Here, the substring() method extracts out the substring ‘Education’ using the start and last indexes.
Different Forms of Java Substring() Method
1. String substring(int startIndex)
It is the first form of substring() method. It returns the substring which starts from the given start index and runs till the end of the string. Here is an example which demonstrates the working of this form,
Note - The index of Java string always starts with 0.
import java.util.*;public class Main { public static void main(String[] args) {// Initializing the StringString mainString = new String("Java is all what we need");// use substring() to extract substringSystem.out.print("The drawn out substring is : ");/*It will start from 12th index and extractthe substring till the last index*/System.out.println(mainString.substring(12));}}
Output
The drawn out substring is : what we need
2. String substring(int startIndex, int lastIndex)
It is the second form of substring() method. It returns the substring which starts from the given start index and runs till (last index -1). Here is an example which demonstrates the working of this form.
import java.util.*;public class Main { public static void main(String[] args) {// Initializing the StringString mainString = new String("Java is all what we need");// use substring() to extract substringSystem.out.print("The drawn out substring is : ");/*It will start from 8th index and extractthe substring till the 20st index*/System.out.println(mainString.substring(8,20));}}
Output
The drawn out substring is : all what we
Various Examples of Java Substring() Method
Let’s discuss how the substring() method will behave in different scenarios.
Example 1: If the values of start index and last index are greater than the length of given string, then substring() method will simply throw “string index out of bound exception”.
import java.util.*;public class Main { public static void main(String[] args) {// Initializing the StringString mainString = new String("Java and Python are good programming languages.");/*substring() method will throw an error/exception after printing the given String. * The values of start index and last index are 100 and 200 respectively * which are even greater than the length of main string.Hence, it will throw "String index of bound" exception*/System.out.print("The given string is : " + mainString);System.out.print("The drawn out substring is : ");System.out.println(mainString.substring(100,200));}}
Output
The given string is : Java and Python are good programming languages.The drawn out substring is : Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin 100, end 200, length 47
at java.base/java.lang.String.checkBoundsBeginEnd(String.java:3319)
at java.base/java.lang.String.substring(String.java:1874)
at Main.main(Main.java:11)
In the above example, the values of start index and last index are even greater than the length of the main string hence, substring() method throws an exception.
Example 2 - If either the value of start index or last index is negative, then substring() method will simply throw “string index out of bound exception”.
import java.util.*;public class Main { public static void main(String[] args) {// Initializing the StringString mainString = new String("Java and Python are good programming languages.");/*substring() method will throw an error/exception after printing the given String.The value of start index and last index are -5 and 10 respectivelySince substring() method can't accept negative index valueso, it will throw "String index of bound" exception*/System.out.print("The given string is : " + mainString);System.out.print("The drawn out substring is : ");System.out.println(mainString.substring(-5,10));}}
Output
The given string is : Java and Python are good programming languages.The drawn out substring is : Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin -5, end 10, length 47
at java.base/java.lang.String.checkBoundsBeginEnd(String.java:3319)
at java.base/java.lang.String.substring(String.java:1874)
at Main.main(Main.java:13)
In the above example, the value of the start index is negative, hence, the substring() method throws an exception.
Example 3 - If the values of both start index and last index are same, then substring() method will return an empty string.
import java.util.*;public class Main { public static void main(String[] args) {// Initializing the StringString mainString = new String("Java and Python are good programming languages.");/*If the value of start index and last index are samethen substring() method will execute successfully and return empty string*/System.out.print("The given string is : " + mainString);System.out.println("The drawn out substring is : ");System.out.println(mainString.substring(3,3));}}
Output
The given string is : Java and Python are good programming languages.The drawn out substring is :
In the above example, since the values of both start and last indexes are the same i.e 3, the substring() method will execute successfully in this case but return an empty string.
How Does the Java Substring() Method Work?
It is very important to know the internal working of the substring() method to understand it properly. As we already know, the substring() method is an implementation of Java string class. When we call the substring() method, then internally Java Virtual Machine produces a new string and stores all the required characters from the given string to this newly created string.
Internal implementation of String substring(int startIndex)
String substring(int startIndex) {
// Check if startIndex is out of bounds
if (startIndex < 0 || startIndex > this.length()) {
throw new StringIndexOutOfBoundsException(startIndex);
}
// Special case: if startIndex is 0, return the original string
if (startIndex == 0) {
return this;
}
// Create a new string from startIndex to the end of the original string
return new String(this.value, startIndex, this.length() - startIndex);
}
Internal implementation of String substring(int startIndex, int lastIndex)
String substring(int startIndex, int endIndex) {
// Check if startIndex and endIndex are out of bounds or if startIndex > endIndex
if (startIndex < 0 || endIndex > this.length() || startIndex > endIndex) {
throw new StringIndexOutOfBoundsException();
}
// Special case: if startIndex and endIndex are equal, return an empty string
if (startIndex == endIndex) {
return "";
}
// Create a new string from startIndex to endIndex (exclusive)
return new String(this.value, startIndex, endIndex - startIndex);
}
Some Applications of Java Substring() Method
The Java substring() method has various applications.
Prefix & suffix extraction
Suppose we need to remove the last name of a person, specific digits after decimal, etc, in all these cases using the substring() method is the best option.
import java.util.*;public class Main {// Java code to illustrate the applications of substring() methodpublic static void main(String[] args) {// Initializing the StringString mainString = new String("124.567");/** using substring() method to remove suffix (.567) from the given string*/System.out.println("The given string is : " + mainString);System.out.print("The drawn out substring is : ");System.out.print(mainString.substring(0,3));}}
Output
The given string is : 124.567
The drawn out substring is : 124
Check if string is Palindrome
Using the substring() method, we can even check whether the given string is palindrome or not. For this, we will reverse the given string using substring() method, then match both the string using equals() method.
public class PalindromeCheck { // Function to reverse a string public static String reverseString(String s) { String reversed = ""; for (int i = s.length() - 1; i > = 0; i--) { reversed += s.charAt(i); } return reversed; }
// Function to check if a string is a palindrome public static boolean isPalindrome(String s) { String reversed = reverseString(s); return s.equals(reversed); }
public static void main(String[] args) { String mainString = "radar"; System.out.println("Is '" + mainString + "' a palindrome? " + isPalindrome(mainString)); }}
Output
Is 'radar' a palindrome? true
Get all possible substrings of a given string
We can make all possible substrings of a given string using the substring() method.
import java.util.*;
public class AllSubstrings { // Java code to illustrate the applications of substring() method // Function to print all substrings of a string public static void GetSubString(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) { // Initializing the String String mainString = "Shiksha"; // calling GetSubString function GetSubString(mainString, mainString.length()); }}
Output
SSh
Shi
Shik
Shiks
Shiksh
Shiksha
h
hi
hik
hiks
hiksh
hiksha
i
ik
iks
iksh
iksha
k
ks
ksh
ksha
s
sh
sha
h
ha
a
Conclusion
Thus, the substring method in Java is a powerful and versatile function for string manipulation, offering various applications in programming.
Contributed by: Vansh Gaur
This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio