23

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)

Slight
  • 1,541
  • 3
  • 19
  • 38
  • Here's a static helper method which allows negatives from my custom `StringUtil` class: `public static String substring(String str, int begin, int end) { if (str == null) [ return null; } if (begin < 0) { begin = str.length() + begin; } if (end < 0) { end = str.length() + end; } return str.substring(begin, end); }`. I also have a `StringUtil.substring(String begin)` which calls the other one with the length of the String for end. – DJDaveMark Apr 04 '19 at 09:12

2 Answers2

47

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:

  1. "beginIndex cannot be negative" -> beginIndex >= 0
  2. "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.)

user2864740
  • 60,010
  • 15
  • 145
  • 220
6

No, using negative numbers for the endindex of substring as well as a number greater than the string length will result in an StringIndexOutOfBoundsException.

(You wouldn't believe how hard it was to find a straight answer to this on the net)

Slight
  • 1,541
  • 3
  • 19
  • 38