No. Negative indices are not allowed.
From String#substring(int beginIndex, int endIndex):
Throws: IndexOutOfBoundsException - if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex.
While the documentation does not directly state that endIndex cannot be negative1, this can be derived. Rewriting the relevant requirements yields these facts:
- "beginIndex cannot be negative" ->
beginIndex >= 0
- "beginIndex must be smaller than or equal to endIndex" ->
endIndex >= beginIndex
Thus it is a requirement that endIndex >= beginIndex >= 0
which means that endIndex cannot be negative.
Anyway, str.substring(0, -x)
can be trivially rewritten as str.substring(0, str.length() - x)
, assuming we have the same idea of what the negative end index should mean. The original bound requirements still apply of course.
1 Curiously, String#subSequence
does explicitly forbid a negative endIndex. Given such, it feels that the documentation could be cleaned up such that both methods share the same simplified precondition text. (As a bonus: there is also an important typo in the "Java 7" subSequence documentation.)