String substring index could be the length of string

java, string, substring

Solution

Because the `endIndex` is exclusive, as specified in the documentation.

IndexOutOfBoundsException - if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex.

I think when I use s.substring(5), it should give me error while it didn't

Why would it be?

Returns a new string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string.

Since the `beginIndex` is not larger than the `endIndex` (5 in your case), it's perfectly valid. You will just get an empty String.

If you look at the source code:

1915  public String substring(int beginIndex) {
1916      return substring(beginIndex, count);
1917  }
....
1941  public String substring(int beginIndex, int endIndex) {
1942      if (beginIndex < 0) {
1943          throw new StringIndexOutOfBoundsException(beginIndex);
1944      }
1945      if (endIndex > count) {
1946          throw new StringIndexOutOfBoundsException(endIndex);
1947      }
1948      if (beginIndex > endIndex) {
1949          throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
1950      }
1951      return ((beginIndex == 0) && (endIndex == count)) ? this :
1952          new String(offset + beginIndex, endIndex - beginIndex, value);
1953  }

Thus `s.substring(5);` is equivalent to `s.substring(5, s.length());` which is `s.substring(5,5);` in your case.

When you're calling `s.substring(5,5);`, it returns an empty String since you're calling the constructor(which is private package) with a `count` value of 0 (`count` represents the number of characters in the String):

644 String(int offset, int count, char value[]) {
645         this.value = value;
646         this.offset = offset;
647         this.count = count;
648 }

Problem

This is a Java string problem. I use the `substring(beginindex)` to obtain a substring. Considering `String s="hello"`, the length of this string is 5. However when I use `s.substring(5)` or `s.substring(5,5)` the compiler didn't give me an error. The index of the string should be from 0 to length-1. Why it doesn't apply to my case? I think that `s.substring(5)` should give me an error but it doesn't.

Original source