It is easier to work with substring
when you think of indexes like this (like letters are between indexes)
H E L L O
0 1 2 3 4 5 <- acceptable range of indexes for "HELLO"
^ ^
| |
start end = length
(min index) (max index)
When you substring from start
to end
you get only characters between these indexes.
So in case of "HELLO".substring(2,4)
you will get part
L L
2 3 4
which returns "LL"
.
Now in case of substring(5)
it acts same as substring(5,length)
which means in this case it is substring(5,5)
. So since 5
index exists in our "model" as acceptable value, and since there are no characters between 5
and 5
we are getting empty string as result.
Similar situation happens in case of substring(0,0)
substring(1,1)
and so on as long as indexes are acceptable by our model.
StringIndexOutOfBoundsException
happens only when we try to access indexes which are not acceptable, which means:
- negative ones:
-1
, -2
, ...
- greater than
length
. Here: 6
7
, ...