当索引1中没有元素时,为什么不跟随java代码抛出java.lang.StringIndexOutOfBoundsException? [英] Why doesn't following java code throw java.lang.StringIndexOutOfBoundsException when there is no element present at index 1?
问题描述
String str="x";
System.out.println(str.substring(1));
来自Javadoc:
String java.lang.String.substring(int beginIndex)
:返回一个新字符串,该字符串是此字符串的子字符串。 子字符串以指定索引处的字符开头,并延伸到此字符串的末尾。
String java.lang.String.substring(int beginIndex)
: Returns a new 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.
推荐答案
看一下 JavaDoc ,并特别注意空虚示例:
Take a look at the JavaDoc, and pay specific attention to the "emptiness" example:
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
如果beginIndex为负或大于此String对象的长度,则抛出异常
;在您的情况下,beginIndex等于字符串的长度,而不是更大。
An exception is throw if beginIndex is negative or larger than the length of this String object
; in your case, beginIndex is equal to the length of your string, and not larger.
这篇关于当索引1中没有元素时,为什么不跟随java代码抛出java.lang.StringIndexOutOfBoundsException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!