Gropai
Gropai

Reputation: 331

Both start index and end index are out of range but the substring method still works in Java

I tried the code "a".substring(1, 1) and it didn't throw an exception. But the start index is 1, which is larger than 0, and because the start index is inclusive, shouldn't it throw an exception?

Similarly, "".substring(0, 0) doesn't crash either, even though 0 should be out of range for an empty string.

Upvotes: 2

Views: 665

Answers (2)

user4398985
user4398985

Reputation:

Essentially, the substring method returns a string (substring) whose length is equal to (end-start), param values: passed in your method.

If end-start = 0, It would return an emptry string. Please see the source code of ORACLE JDK1.7

public String substring(int beginIndex, int endIndex) {
        if (beginIndex < 0) {
            throw new StringIndexOutOfBoundsException(beginIndex);
       }
        if (endIndex > count) {
            throw new StringIndexOutOfBoundsException(endIndex);
        }
        if (beginIndex > endIndex) {
            throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
        }
        return ((beginIndex == 0) && (endIndex == count)) ? this :
            new String(offset + beginIndex, endIndex - beginIndex, value);
    }

It would raise an IndexOutOfBoundsException only when this happens:

*

if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex.

*

Upvotes: 0

Kennedy Oliveira
Kennedy Oliveira

Reputation: 2291

Acording to the documentation of the method:

Throws: IndexOutOfBoundsException - if beginIndex is negative or larger than the length of this String object.

The length of your string is 1 and not 0, so it doens't throw and exception.

Upvotes: 10

Related Questions