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

Categories

0 votes
397 views
in Technique[技术] by (71.8m points)

java - What will be the output of String.substring(String.length)?

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

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

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...