-1

This code...

public String a() {
String x = "abc";
String y = x.substring(3,3);
return y; //returns : "" 
}

Works without errors but i thought there is no 3rd index for that string.As i understand indexes of strings like 1st char is 0 index ,2nd char 1 index,it goes like that.Then why is not that giving me a error like "OutOfBoundsException"?

0

2 Answers 2

0

Have a look at the code, and you will see that it does not meet the requirement for an Exception

 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);
}
Sign up to request clarification or add additional context in comments.

Comments

0

From the documentation:

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

None of these conditions have been met.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.