substring Method in Java (with examples)
Every once in a while, you may have come across substring()
method in Java, it is less intuitive than you think. You may imagine it just grabs some part of the string and returns it as a substring, so what exactly is the catch here? Let’s find it out in this article!
Introduction
A string is a collection of characters enclosed in double quotes (” “). It represents a sequence of characters.
For example –
String name = "Vineeta Tiwari"
Code language: Java (java)
Here, we have created a string named name
which contains “Vineeta Tiwari” as a value. The length of the string can be found using the length()
method.
In Java, Strings are immutable, that means, String once created is unmodifiable, you cannot change it. The reason why it is immutable is that, suppose you have five reference variables pointing to one object- “Anjali”, if the value of the object is changed by one reference variable then all the reference variables will be affected, that is why the immutability of strings is important.
In Java runtime, we have a String pool maintained. It is possible only because of string’s immutability. Because of this, we save a lot of heap space because different String variables can refer to the same String variable present in the pool. String immutability helps in making our application more secure. Say you have passed your username and password in the database as String, you’d want that nobody can change your data and that’s exactly what String helps us in. Its immutability doesn’t let the value be changed.
What is substring() method in Java?
substring()
method is a part of the Java String class and returns part of the string. You can specify mainly two parameters here- startIndex and endIndex, where startIndex is inclusive and endIndex is exclusive, which means startIndex
will include the index specified and endIndex
will not include the index specified. We can also just specify the startIndex
and it will return the characters from that index till the end.
For example –
Type 1:- If we specify both startIndex
and endIndex
Type 2:- If we specify only startIndex
public class Example{
public static void main(String args[]){
String str="example";
System.out.println(str.substring(2,4));//returns ap
System.out.println(s1.substring(2));//returns ample
}}
Code language: Java (java)
substring()
method helps us in getting the desired subset of the string.
Exceptions
You need to be careful while specifying the parameters of the substring()
method as it may throw StringIndexOutOfBoundsException if you make any of the following mistakes –
- specifying
startIndex
as negative. The index can never be negative startIndex
is greater than theendIndex
. This is against the signature rules of thesubstring()
method.- If your
startIndex
orendIndex
is greater than the length of the string i.e. total number of characters present in the string
Advantages
substring()
method comes in very handy when you want to extract the prefix or suffix of a string. Say you have been given a list of names and want to extract the names with the surnames ‘Kumar’. Then all you need to do is extract the surnames using thesubstring()
method and check whether the names have a surname equal to ‘Kumar’ or not.
public class Surname_Subtring
{
// main method
public static void main(String argvs[])
{
String str[] =
{
"Yash Kumar",
"Praveen Singh",
"Ravi Kumar",
"Gurjit Singh",
"Narender Saini",
"Rohit Sharma",
"Sandeep Kumar",
"Milkha Singh"
};
String surName = "Kumar";
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]);
}
}
}
}
Code language: Java (java)
#OUTPUT -
Yash Kumar
Ravi Kumar
Sandeep Kumar
Code language: Java (java)
- To get all the substrings of the string, we can use
substring()
method
public class Get_Substring {
public static void SubString(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)
{
String s = "abcd";
SubString(s, s.length());
}
}
Code language: Java (java)
#OUTPUT
a
ab
abc
abcd
b
bc
bcd
c
cd
d
Code language: CSS (css)
- If you want to check whether your string is a palindrome string or not, you can use
substring()
method. A palindrome string is a string that remains the same even if we reverse it i.e. it reads the same both ways
public class Palindrome_Substring {
public static void main(String[] args) {
System.out.println(checkPalindrome("aabaa"));
System.out.println(checkPalindrome("abcd"));
System.out.println(checkPalindrome("121"));
System.out.println(checkPalindrome("BBBB"));
}
private static boolean checkPalindrome(String s) {
if (s == null)
return false;
if (s.length() <= 1) {
return true;
}
String first = s.substring(0, 1);
String last = s.substring(s.length() - 1);
if (!first.equals(last))
return false;
else
return checkPalindrome(s.substring(1, s.length() - 1));
}
}
Code language: Java (java)
#OUTPUT-
true
false
true
true
Code language: Java (java)
Conclusion
In this article, we discussed Strings and its substring()
method and its properties.
I hope you have understood the concept!
Thanks for reading!
Sharing is caring
Did you like what Vineeta Tiwari wrote? Thank them for their work by sharing it on social media.
No comments so far
Curious about this topic? Continue your journey with these coding courses: