Can negative one be used as the end index for string.substring in Java?
Example:
String str = "test"; str.substring(0, str.indexOf("q"));
Edit: Nowhere in the javadocs does it say directly that endindex cannot be negative. There are implementations of substring in other languages and libraries that allow a negative endindex but disallow a negative beginindex, so it seems relevant that this be explicitly stated. It is not in any way implied either. (Edit: ok it is implied loosely, but I and apparently others who have asked me this question in person still find it pretty unclear. This was meant to be a simple Q+A that I provided not me actually trying to find an answer to this trivial question)
The start position that you specify for the SUBSTR function can be a positive or a negative number. However, the SUBSTR function treats a negative number in the start position differently than does the SUBSTRING function.
No, never. length is unsigned number, it can't be negative.
If a parameter is negative, the position is counted from the end of the string. substring() is similar to slice(). The difference is that substring() cannot accept negative indexes.
As the Java String index starts from zero, it should not accept negative integers in the index. So the program must throw an exception. The type of error should again be the “String index out of range” exception because the specified index is not present in the main String.
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 >= 0
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With