The Java String.substring() method is used to extract a specific portion or subset of an existing string. Because strings in Java are immutable, this method does not modify the original string; instead, it returns a new String object containing the extracted characters.
Java String.substring() method is an overloaded method that provides the following two variants:
public String substring(int startIndex) // type - 1
and,
public String substring(int startIndex, int endIndex) // type - 2
If we do not specify endIndex, the method returns all the characters from startIndex.
startIndex: The starting index is inclusive.
endIndex: Ending index is exclusive.
The method returns a new string that represents the specified portion of the original string. It does not modify the original string but instead creates a new string containing the characters from the specified starting index to the specified ending index.
It throws StringIndexOutOfBoundsException if any one of the following conditions is met:
public String substring(int beginIndex)
{
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
int subLen = value.length - beginIndex;
if (subLen < 0) {
throw new StringIndexOutOfBoundsException(subLen);
}
return (beginIndex == 0) ? this : new String(value, beginIndex, subLen);
}
public String substring(int beginIndex, int endIndex)
{
if (beginIndex < 0)
{
throw new StringIndexOutOfBoundsException(beginIndex);
}
if (endIndex > value.length)
{
throw new StringIndexOutOfBoundsException(endIndex);
}
int subLen = endIndex - beginIndex;
if (subLen < 0)
{
throw new StringIndexOutOfBoundsException(subLen);
}
return ((beginIndex == 0) && (endIndex == value.length)) ? this : new String(value, beginIndex, subLen);
}
public class Main {
public static void main(String args[])
{
String s1="TpointTech";
System.out.println(s1.substring(2, 4)); //returns oi
System.out.println(s1.substring(2)); //returns ointTech
}
}
Output:
oi ointTech
public class Main {
public static void main(String[] args) {
String s1="TpointTech";
String substr = s1.substring(0); // prints the complete string
System.out.println(substr);
String substr2 = s1.substring(5,10); // prints string from index 5 to index 10
System.out.println(substr2);
String substr3 = s1.substring(5,15); //throws Exception because string is not 15 character long
}
}
Output:
TpointTech tTech Runtime Error: Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin 5, end 15, length 10 at java.base/java.lang.String.checkBoundsBeginEnd(String.java:3720) at java.base/java.lang.String.substring(String.java:1909) at Main.main(Main.java:8)
While the String.substring() method is powerful, there are some key considerations to keep in mind:
Java uses zero-based indexing, meaning the first character in a string is at index 0. When specifying indices for a substring, ensure that they fall within the valid range (0 to length - 1) to avoid IndexOutOfBoundsException.
In Java, String are immutable objects, meaning their values cannot be changed once created. The method returns a new string, leaving the original string unchanged.
The String.substring() method can be used to do some prefix or suffix extraction. For example, we can have a list of names, and it is required to filter out names with surname as "singh".
public class Main
{
public static void main(String argvs[])
{
String str[] =
{
"Sir Donald Bradman",
"Ricky Ponting",
"Shane Warne",
"Glenn McGrath",
"Allan Border",
"Adam Gilchrist"
};
String surName = "Warne";
int surNameSize = surName.length();
int size = str.length;
for(int j = 0; j < size; j++)
{
int length = str[j].length();
// extracting the surname
String subStr = str[j].substring(length - surNameSize);
// checks whether the surname is equal to "Singh" or not
if(subStr.equals(surName))
{
System.out.println(str[j]);
}
}
}
}
Output:
Shane Warne
The String.substring() method can also be used to check whether a string is a palindrome or not.
public class Main
{
public boolean isPalindrome(String str)
{
int size = str.length();
// handling the base case
if(size == 0 || size == 1)
{
// an empty string
// or a string of only one character
// is always a palindrome
return true;
}
String f = str.substring(0, 1);
String l = str.substring(size - 1);
// comparing first and the last character of the string
if(l.equals(f))
{
// recursively finding the solution using the substring() method
// reducing the number of characters of the by 2 for the next recursion
return isPalindrome(str.substring(1, size - 1));
}
return false;
}
// main method
public static void main(String argvs[])
{
// instantiating the class SubstringExample4
SubstringExample4 obj = new SubstringExample4();
String str[] =
{
"madam",
"rock",
"eye",
"noon",
"kill"
};
int size = str.length;
for(int j = 0; j < size; j++)
{
if(obj.isPalindrome(str[j]))
{
System.out.println(str[j] + " is a palindrome.");
}
else
{
System.out.println(str[j] + " is not a palindrome.");
}
}
}
}
Output:
madam is a palindrome. rock is not a palindrome. eye is a palindrome. noon is a palindrome. kill is not a palindrome.
We request you to subscribe our newsletter for upcoming updates.