Why doesn't following java code throw java.lang.StringIndexOutOfBoundsException when there is no element present at index 1?

后端 未结 1 1784
盖世英雄少女心
盖世英雄少女心 2021-01-24 12:25
String str=\"x\";
System.out.println(str.substring(1));

From Javadoc:

String java.lang.String.substring(int beginIndex)

1条回答
  •  伪装坚强ぢ
    2021-01-24 12:54

    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
    

    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.

    0 讨论(0)
提交回复
热议问题