
In this comprehensive guide, we will help you understand substrings in Java in depth. We will not only provide theoretical explanations but also real code examples to help you visualize key concepts.
We will teach you:
- How to create substrings in Java
- Useful methods to find and manipulate substrings
- How to check if a substring exists within a larger string
- Finding the index and last index of a substring
But before we dive into working with substrings, let‘s ensure we have a solid grasp of some core concepts.
What are Strings and Substrings in Java?
In Java, a string represents a sequence of characters. Strings are objects in Java that can contain letters, numbers, symbols and even whitespace.
A substring is a portion or subset of a larger Java string.
For example:
- "Geek" is a substring of "GeekFlare"
- "John" is a substring of "John Doe"
Substrings allow you to extract a specific part of a string. If you only wanted the first name "John" from the full name "John Doe", substrings make that easy.
You can also use substrings to check if a string contains a specific word or phrase. For example, you could check if a string contains the substring "Hello" before processing it further.
Now that we understand the basics, let‘s explore how to actually create and use substrings in Java.
Creating Substrings in Java
There are a few different ways to generate substrings in Java strings:
- Using the
substring()method - Using the
split()method
Let‘s look at each approach.
The substring() Method
The substring() method allows you to easily extract a substring from a larger string. It takes one or two parameters:
startIndex– The beginning index of the substringendIndex(optional) – The ending index of the substring
Here is the basic syntax:
String substring = originalString.substring(startIndex, endIndex);
Let‘s look at some examples to understand this better.
substring(int startIndex)
This version only takes a single startIndex parameter. It returns a substring starting from that index to the end of the original string.
String str = "GeekFlare";
String sub = str.substring(4);
// sub = "Flare"
Here we are extracting a substring from index 4 to the end of "GeekFlare", which gives us "Flare".
substring(int startIndex, int endIndex)
This version takes both a startIndex and endIndex. It returns a substring starting from startIndex up to BUT not including endIndex.
So the character at endIndex is NOT part of the returned substring.
String str = "GeekFlareFans";
String sub = str.substring(4, 9);
// sub = "Flare"
Here we extracted index 4 up to index 8, which gives us "Flare". Index 9 (the letter F) is not included.
One important thing to note about substring() is that if you supply an invalid index, you will get an StringIndexOutOfBoundsException error.
Always double check that the indexes fall within the length of the string when using this method.
The split() Method
The split() method offers another option to extract substrings from a larger string. It divides a string based on a provided regular expression or "regex" delimiter parameter.
Here is the basic syntax:
String[] substrings = originalString.split(regex);
This splits the string on every occurrence of the given regular expression and stores the resulting substrings in a String array.
Let‘s look at some examples.
split(String regex)
This version only takes the regex delimiter. It splits the string on that delimiter with no limits, storing all results in the array.
String str = "Geek%Flare";
String[] subs = str.split("%");
// subs[0] = "Geek"
// subs[1] = "Flare"
Here we are splitting on the % character into an array containing the two substrings "Geek" and "Flare".
One thing to note is that split() will return all empty strings at delimiters that occur consecutively.
For example:
str = "Geek%Flare%code";
String[] subs = str.split("%");
// subs[0] = "Geek"
// subs[1] = "Flare"
// subs[2] = "" (empty string)
// subs[3] = "code"
The two consecutive % signs result in an empty string at index 2 in the returned array.
split(String regex, int limit)
This overload allows you to specify a limit parameter to restrict the number of splits performed.
The limit winds up being the maximum size of the returned substring array.
String str = "Geek%Flare%code%now";
String[] subs = str.split("%", 2);
// subs[0] = "Geek"
// subs[1] = "Flare%code%now"
Here we limited it to 2 splits maximum. So we omit "code" and "now", keeping them bundled in the remainder substring instead.
The split() method is useful when you need to divide up strings in a precise way. It gives you added flexibility to control exactly how many substrings are returned.
Checking for the Existence of a Substring
Often you need to check if a specific substring exists within a larger string. Java offers a couple handy methods to accomplish this:
contains()
The contains() method checks if the string contains the specified substring. It returns a simple true/false boolean:
String str = "Hello World!";
if(str.contains("World")) {
// Substring found!
} else {
// Substring NOT found
}
contains() provides an easy way to validate the existence of a substring.
indexOf()
The indexOf() method returns the index of the first occurrence of the specified substring:
String str = "Hello World!";
int index = str.indexOf("World"); // 6
It returns -1 if the substring is NOT found.
So you can also use indexOf() in boolean checks:
if(str.indexOf("World") > -1) {
// Substring exists
} else {
// Substring doesn‘t exist
}
Checking the index against -1 lets you validate if the substring was found or not.
Between these two methods you have simple options for validating substring existence.
Finding a Substring‘s Index in Java
In addition to just checking if a substring exists, you often need to know exactly where it exists within a string.
Java provides three helpful methods to find a substring‘s precise index or position:
indexOf()
As shown above, indexOf() returns the index of first occurrence of the given substring:
String str = "Hello World!";
int index = str.indexOf("World"); // 6
It‘s useful for finding the substring location.
lastIndexOf()
lastIndexOf() gives you index of the last occurrence of substring instead:
String str = "Hello World! Hello";
int index = str.lastIndexOf("Hello"); // 15
This can be handy for cases where substring repeats.
indexOf() and lastIndexOf() Compared
Both methods serve a similar purpose – locating substrings and their indexes. But they find the first vs last occurrence respectively.
When would you pick one over the other?
indexOf() is great when…
- You only care about the first match
- You want to start processing from the first match onward
lastIndexOf() comes in handy for cases like:
- The last match holds more relevance
- You want to process text leading up to final occurrence
So think about which index needs priority in your specific use case when deciding between them.
Substring FAQs
Here are some common questions about working with substrings in Java:
How do I prevent split() from returning empty strings?
Pass a limit argument of 0. This discards trailing empty splits:
str.split("%", 0);
Does indexOf() return indexes of all substring matches?
No, only the first match. For all matches, you need to call in loop, checking each subsequent result.
What happens if I pass invalid indexes to substring()?
You will get a StringIndexOutOfBoundsException error. Double check index boundaries.
Conclusion
Working with substrings is very common in most Java string operations. This guide covered core concepts like:
- Generating substrings via
substring()andsplit() - Checking substring existence using
contains()andindexOf() - Finding precise substring indexes with
indexOf()andlastIndexOf()
Practice the examples yourself to get comfortable with practical substring usage.
For more Java string practice, check out these example Java string programs or our Java regex tutorial.