Jason Miller
Jason Miller

Reputation: 57

Why this is not StringIndexOutOfBounds?

public String delDel(String str) {
  if (str.length() < 4)
  return str;
  if (str.substring(1,4).equals("del"))
  return str.substring(0, 1) + str.substring(4, str.length());
  else
  return str;
}

If I run delDel("adel"), it returns a, however, the length of adel is 4, which means the last character string index is 3, why isn't str.substring(4, str.length() out of bounds?

Upvotes: 4

Views: 145

Answers (1)

Amin Heydari Alashti
Amin Heydari Alashti

Reputation: 1021

The below code is the implementation of the substring method of String class in java:

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

As can be seen, the beginIndex is only checked not be be less than zero, and the endIndex is only checked against the "value.length" of the string to be large than it. Then, if this condition passes, then the requested substring would be created by below Code:

public String(char value[], int offset, int count) {
    if (offset < 0) {
        throw new StringIndexOutOfBoundsException(offset);
    }
    if (count <= 0) {
        if (count < 0) {
            throw new StringIndexOutOfBoundsException(count);
        }
        if (offset <= value.length) {
            this.value = "".value;
            return;
        }
    }
    // Note: offset or count might be near -1>>>1.
    if (offset > value.length - count) {
        throw new StringIndexOutOfBoundsException(offset + count);
    }
    this.value = Arrays.copyOfRange(value, offset, offset+count);
}

In your case, because the count would become zero(4-4), then 'this.value = "".value;'

Upvotes: 1

Related Questions