Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why from index is inclusive but end index is exclusive?

Tags:

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?

like image 929
Maniganda Prakash Avatar asked Jun 14 '11 04:06

Maniganda Prakash


People also ask

Is substring exclusive or 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.

Is substring in Java inclusive 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 is inclusive and exclusive in python?

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]

How do you use substring in Java?

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.


1 Answers

Because:

  • Java is based on C, and C does it this way
  • It makes the code cleaner: If you want to capture to end of object, pass object.length (however the object implements this, eg size() etc) into the toIndex parameter - no need to add/subtract 1

For 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.

like image 179
Bohemian Avatar answered Oct 07 '22 20:10

Bohemian