In Java API methods like:
String.substring(int beginIndex, int endIndex)
String.subSequence(int beginIndex, int endIndex)
List.subList(int fromIndex, int toIndex)
Why is the beginning index inclusive but the end index exclusive? Why shouldn't they have been designed both inclusive?
Java String class provides the built-in substring() method that extract a substring from the given string by using the index values passed as an argument. In case of substring() method startIndex is inclusive and endIndex is exclusive.
The Java String class substring() method returns a part of the string. We pass beginIndex and endIndex number position in the Java substring method where beginIndex is inclusive, and endIndex is exclusive. In other words, the beginIndex starts from 0, whereas the endIndex starts from 1.
What does this mean? If an index is inclusive, then that number will be included in the selection, while an exclusive will not be. Say, for example, we have the following list and two list slices. list = [0, 1, 2, 3, 4, 5] list1 = list[:3] # [0, 1, 2] list2 = list[4:] # [4, 5]
The substring(int beginIndex, int endIndex) method of the String class. It returns a new string that is a substring of this string. 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.
Because:
object.length
(however the object implements this, eg size() etc) into the toIndex parameter - no need to add/subtract 1For example:
String lastThree = str.substring(str.length() - 3, str.length());
This way, it is very obvious what is happening in the code (a good thing).
EDIT An example of a C function that behaves like this is strncat
from string.h
:
char *strncat(char *dest, const char *src, size_t n);
The size_t
parameter's value corresponds to the java endPosition
parameter in that they are both the length of the object, but counting from 0 if they are the index, it would be one byte beyond the end of the object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With