Possible Duplicate:
why from index is inclusive but end index is exclusive?
substring() method => String substring(int beginIndex, int endIndex)
Description:
Returns a new string that is a substring of this string. The first
integer argument specifies the index of the first character. The
second integer argument is the index of the last character – 1.
Take a look at the following code:
String anotherPalindrome = "Niagara. O roar again!";
String roar = anotherPalindrome.substring(11, 15);
Output: roar
Now, if the JVM didn’t substract int endIndex by one, we could just use substring(11,14) instead, wouldn’t that be much more convenient and less error-prone (human side)? Had you not read the description carefully, you might just ended up scratching your head for half an hour (like I did) when you thought that endIndex is just the normal index. What’s the reason for the Java language creators to subtract it by one?
It has several advantages:
is always correct. Also:
The size of resulting string is always
j - i. More specificallys.substring(0, j)will always returnjcharacters. Finally this means that if you want to takencharacters after indexiyou simply say:It’s also easier to extract suffix of a string (last
ncharacters):For example extracting file extension: