Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

public class Str {

    public static void main(String[] args) {

        String str = "abcde";
        String s = str.substring(str.length());
        System.out.println(s);
    }

}

The index of character 'e' is 4, but I am trying to get the whole string of length 5. If I execute the code above, why it is not throwing the IndexOutOfBoundsException?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
401 views
Welcome To Ask or Share your Answers For Others

1 Answer

The JavaDoc for String.substring() states:

[throws] IndexOutOfBoundsException - if beginIndex is negative or larger than the length of this String object.

Since your beginIndex is equal to the length of the string it is a valid value and substring() returns an empty string.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...