In this article, we’ll talk about Java substring method of String class.
1. What is substring Method in Java?
The substring method lives under the String class and allows you to retrieve a substring of a specific string. It has two overloaded methods:
- The first accepts only an integer which is the start of the substring inclusive and it returns the substring
- While the second one, accepts 2 integers, the start(inclusive) and end index(exclusive) and it returns the substring
2. How to use substring method – Java substring Example
In this section, we’ll go through 3 examples; one for each version of substring(), and a third on how to call substring by using a Java 8 Function.
2.2 String substring(int beginIndex)
String ylc = "You Learn Code is the best"; int index = ylc.indexOf("Code"); System.out.println(ylc.substring(index));
Here we retrieve the index in which the word “Code” starts, and then we used that index inside substring
method; as a result, we will get the following string printed:
Code is the best
2.2 String substring(int beginIndex, int endIndex)
String ylc = "You Learn Code is the best"; int indexStart = ylc.indexOf("Code"); int indexEnd = ylc.indexOf(" best"); System.out.println(ylc.substring(indexStart, indexEnd));
In this case, we retrieved both the start and the end index. Note that since the endIndex is exclusive, the space will not be included in the result:
Code is the
Finally, note that there is no point in setting the endIndex
as string.length()
since it will be exactly the same as the one-parameter version of substring.
2.3 Using wrong Indices
If we use a negative index or any index which is > string.length() + 1, we will get:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: Range [x, y) out of bounds for length z
2.4 Creating a Java 8 Substring Function
Finally, if for whatever reason you’d like to create a function that uses substring, you could do it like this:
@FunctionalInterface public interface SubstringFunction<Integer, String> { String apply(Integer start, Integer end, String input); } SubstringFunction<Integer, String> substringFunction = (start, end, input) -> input.substring(start, end);
Here we created a Functional Interface and we implemented it by using a lambda expression. Then, we can call it as shown below:
String ylc = "You Learn Code is the best"; int indexStart = ylc.indexOf("Code"); int indexEnd = ylc.indexOf(" best"); System.out.println(substringFunction.apply(indexStart, indexEnd, ylc));
and the result will be the same as in section 2.2
3. Conclusion
By now, you should be able to use substring()
method of String
class either by providing a beginIndex and/or an endIndex. Should you like to learn more about the String class, click here.