The substring() method in Java is a powerful tool for extracting parts of a string. This method always returns a new string, and the original string remains unchanged because String is immutable in Java.
In this tutorial, we’ll cover its syntax, use cases, and potential pitfalls while providing practical examples and solutions to common errors.
Parameters:
beginIndex
- the starting index (inclusive).
endIndex
(optional) - the ending index (exclusive).
Java String substring method is overloaded and has two variants.
substring(int beginIndex)
: This method returns a new string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string.substring(int beginIndex, int endIndex)
: The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is (endIndex - beginIndex).IndexOutOfBoundsException
if any of the below conditions met.
substring()
ExampleHere is a simple program for the substring in java.
Output of the above substring example program is:
We can use the substring()
method to check if a String is a palindrome or not.
Here we are checking if the first letter and the last letter is the same or not. If they are not the same, return false. Otherwise, call the method again recursively passing the substring with the first and last letter removed.
You can checkout more string examples from our GitHub Repository.
Here is a table comparing various use cases of the substring() method.
Use Case | Description | Example |
---|---|---|
Extracting a part of a string | Extracts a part of a string based on start and end indices. | String part = "substringExample".substring(0, 10); |
Validating a string prefix | Checks if a string starts with a specific prefix. | if ("substringExample".substring(0, 3).equals("sub")) { ... } |
Validating a string suffix | Checks if a string ends with a specific suffix. | if ("substringExample".substring("substringExample".length() - 3).equals("ple")) { ... } |
Checking for a palindrome | Checks if a string is the same forwards and backwards. | boolean isPalindrome = "madam".substring(0, 1).equals("madam".substring("madam".length() - 1)); |
StringIndexOutOfBoundsException
ErrorsThe substring()
method throws a StringIndexOutOfBoundsException
if:
The beginIndex
is negative.
The endIndex
is greater than the string length.
If the beginIndex
> endIndex
.
Solution: Always validate indices before calling substring()
.
substring()
with Null or Empty StringsSolution: Check for null
before calling substring()
.
So, here is the final code block:
Error Type | Cause | Solution |
---|---|---|
StringIndexOutOfBoundsException |
Using an index out of range | Validate index before calling substring() |
NullPointerException |
Calling substring() on null |
Check for null before calling substring() |
Performance Issues | Using substring() frequently in large strings |
Consider StringBuilder or StringBuffer |
substring()
substring()
with split()
Feature | substring() | split() |
---|---|---|
Use Case | Extracts a part of a string | Splits a string into multiple parts |
Performance | Faster for simple extractions | Slower due to regex processing |
Returns | Substring | Array of substrings |
The substring()
method is a built-in function in Java’s String class. You can use string.substring(startIndex, endIndex)
to extract a portion of a string. Here’s an example code block to illustrate its usage:
You can use Java Streams to extract substrings from a list:
charAt()
in Java?The charAt(int index)
method in Java returns the character at a specified index in a string.
Use substring(beginIndex, endIndex)
:
The substring()
method is the best way to extract parts of a string. Here’s an example of how to use it:
Another approach is using split()
if you need multiple parts. Here’s an example of how to use it:
substring()
and split()
in Java?The substring()
method extracts a single portion of a string, while split()
divides a string into an array based on a delimiter.
Yes, substring()
can throw a StringIndexOutOfBoundsException
if the indices are invalid. Always validate your indices before calling substring()
. Here’s an example of how to validate indices and avoid this exception:
In conclusion, extracting parts of a string in Java is a crucial skill for any developer. The substring()
method is a powerful tool for extracting a single portion of a string, while split()
is useful for dividing a string into multiple parts based on a delimiter. It’s essential to understand the differences between these methods and how to use them effectively in your code.
Additionally, being aware of the potential for StringIndexOutOfBoundsException
when using substring()
and taking steps to validate indices can help prevent errors in your code. By mastering these techniques, you’ll be able to manipulate strings with ease and write more efficient, effective code.
For further reading, check out these related Java tutorials:
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
Hello Pankaj I want to understand negative indexing in strings, If it starts from -1 at the end of the string, it should go on -1,-2,-3 so on from right to left.what does 0th index represent then? I don’t understand the 3rd example here. I looked it up but haven’t found anything useful so far. ex: var str = ‘The morning is upon us.’; str.slice(-3); // returns ‘us.’ str.slice(-3, -1); // returns ‘us’ str.slice(0, -1); // returns 'The morning is upon us’1234
- Bindu Yadav