Learn to get a substring from from given String in Java between the two indices. Note that String is character array based type and the first character of String is at 0 index.
If we store a String “Hello World” in Java, then it creates a character array of size 11 in the memory to store all the characters of the String value.
String str = "Hello World";
The following is a pictorial representation of the array in memory.
1. String.substring() APIThe String.substring() in Java returns a new String that is a substring of the given string that begins from startIndex to an optional endIndex. These indices determine the substring position within the original string.
The substring() method takes two arguments:
String substring(int beginIndex)
String substring(int beginIndex, int endIndex)
The method returns the substring between the valid start and end indices. If the indices are not valid then we can get IndexOutOfBoundsException error in the runtime.
2. Substring ExamplesLet us see a few examples to understand how the substring() method works.
2.1. Using beginIndex and endIndexPass both indices (begin and end indices) when we need to find a substring starting from the given index position to the given end index position. Please note that:
In the following program, we are finding the substring between the indices 0 and 5. Remember that end index is exclusive, so the character at end index is not included in the substring. In this case, the character at end index is whitespace.
Similarily, we can search for the substring between indices 2 to 8.
Assertions.assertEquals("llo Wo", str.substring(2, 8));
2.2. Using only beginIndex
When we do not pass the endIndex argument, the substring is taken up to the last character of the string. In other words, if not specified, the value of endIndex is always ‘string.length() – 1’.
In the following example, we are getting the substring from index position 6.
Assertions.assertEquals("World", str.substring(6));
3. IndexOutOfBoundsException
As mentioned earlier, if we pass an invalid index (such as negative index value) that does not exist in the character array, or the begin index is greater than end index then we will get the IndexOutOfBoundsException in runtime.
Assertions.assertThrows(IndexOutOfBoundsException.class, () -> { //invalid index
str.substring(-1);
});
Assertions.assertThrows(IndexOutOfBoundsException.class, () -> { //begin index > end index
str.substring(6, 4);
});
4. Conclusion
In this short Java tutorial, we learned to get the substring of a specified string using the begin and end indices. We learned the rules about valid index values, and begin index is inclusive and end index is exclusive.
Happy Learning !!
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4