Why is “out of range” not thrown for 'substring(startIndex, endIndex)'

后端 未结 6 995
生来不讨喜
生来不讨喜 2020-11-27 08:02

In Java I am using the substring() method and I\'m not sure why it is not throwing an \"out of index\" error.

The string abcde has index st

6条回答
  •  春和景丽
    2020-11-27 08:28

    According to the Java API doc, substring throws an error when the start index is greater than the Length of the String.

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

    In fact, they give an example much like yours:

    "emptiness".substring(9) returns "" (an empty string)
    

    I guess this means it is best to think of a Java String as the following, where an index is wrapped in |:

    |0| A |1| B |2| C |3| D |4| E |5|
    

    Which is to say a string has both a start and end index.

提交回复
热议问题