当索引1中没有元素时,为什么不跟随java代码抛出java.lang.StringIndexOutOfBoundsException?

时间:2015-07-11 18:19:44

标签: java string

String str="x";
System.out.println(str.substring(1));

来自Javadoc:

  

String java.lang.String.substring(int beginIndex):返回一个新字符串,该字符串是该字符串的子字符串。 子字符串以指定索引处的字符开头,并延伸到此字符串的末尾。

1 个答案:

答案 0 :(得分:5)

看一下JavaDoc,并特别注意“空虚”的例子:

Returns a string that is a substring of this string. The substring begins
with the character at the specified index and extends to the end of
this string. 

Examples: 

 "unhappy".substring(2) returns "happy"
 "Harbison".substring(3) returns "bison"
 "emptiness".substring(9) returns "" (an empty string)

Parameters:
beginIndex the beginning index, inclusive.
Returns:
the specified substring.
Throws:
IndexOutOfBoundsException - if beginIndex is negative or larger than
                            the length of this String object

异常是抛出if beginIndex is negative or larger than the length of this String object;在您的情况下,beginIndex等于字符串的长度,而不是更大。