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?
Because:
object.length(however the object implements this, eg size() etc) into the toIndex parameter – no need to add/subtract 1For example:
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
strncatfromstring.h:The
size_tparameter’s value corresponds to the javaendPositionparameter 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.