Reputation: 73
When was testing some code, I noticed that the substring method wouldn't throw an exception if the index I used was equal to the length of the string. For example:
String s = "holy";
System.out.println(s.substring(4));
The output would return nothing, but it wouldn't throw an exception. But if I tried to call:
String s = "holy";
System.out.println(s.substring(5));
It would throw an IndexOutOfBoundsException. I read the Javadoc for the method and it says
if beginIndex is negative or larger than the length of this String object.
Anyone know why it allows for the beginning index to be equal to the string length?
Upvotes: 1
Views: 2065
Reputation: 109015
There is basically one reason for this, in substring(int beginIndex, int endIndex)
, if beginIndex == endIndex
then the result is an empty string. So given that property, and the fact that the maximum value of endIndex
is the string length, then allowing string.substring(string.length(), string.length())
should be allowed and return an empty string as well. And this last can be simplified to string.substring(string.length())
.
Allowing the length as a valid begin index also provides a number of nice properties:
"".substring(0)
returns ""
String start = string.substring(0, n)
and String end = string.substring(n)
results in the following:
n = 0
: start = ""
, end = string
n = string.length()
: start = string
, end = ""
Disallowing this and throwing an exception would require all kinds of additional bounds checks in string manipulation code (and in substring itself for that matter).
Upvotes: 1
Reputation: 140319
Think about other invocations of substring
:
"holy".substring(n)
can be visualized as copying the range of characters between n
(inclusive) and the end of the string (exclusive).
For example:
"holy".substring(0)`
h o l y
O-------X (O = start, X = end)
0 1 2 3 4
That is, the start position is just before the character, and the end position is just after the character. The resulting length of the string is end - start
, 4 in this case.
and
"holy".substring(1)
h o l y
O-----X // length = 4 - 1 = 3.
0 1 2 3 4
etc. Then:
"holy".substring(4)
can be visualized as
h o l y
O // O and X are at the same position
X // length = 4 - 4 = 0
0 1 2 3 4
It's fine that O and X are at the same position: it just means the result is a zero-length string, ""
.
But, increase the index to 5:
"holy".substring(5)
h o l y
X-O // O is after X
// length = 4 - 5 = -1 (?!)
0 1 2 3 4 5
A string of length -1 doesn't make sense, hence the exception.
Upvotes: 5
Reputation: 312
Upvotes: 0