So, I am trying to figure out why String.substring(int startIndex) allows a start index that is out of bounds and does not throw OOB exception?
Here is the code I was testing this with :
public class testSub {
public static void main(String[] args) {
String testString = "D";
String newSub= testString.substring(1); //print everything FROM this index Up, right? Should that not be out of bounds? Yet I just get a blank.
System.out.println(newSub); //this works fine and prints a blank
System.out.println(testString.charAt(1)); // <Yet this throws OOB?
System.out.println(testString.lastIndexOf("")); // Gives me (1) but I just tried getting it? Should this not mean String length is 2?
}
}
I understand that substrings are substring(inclusive, exclusive), but 1 is clearly out of bounds, so WHY is it giving a blank space instead of throwing OOB, or how is it doing it? Is "" some special exception?
As per JavaDoc, the substring method will only throw exception if index is > length of the string object. The chart method will throw exception only if index is NOT LESS than the length of the object.
Substring method(int beginIndex)
Parameters: beginIndex the beginning index, inclusive. Returns: the specified substring. Throws: IndexOutOfBoundsException - if beginIndex is negative or larger than the length of this String
ChartAT Method
Returns the char value at the specified index. An index ranges from 0 to length() - 1. The first char value of the sequence is at index 0, the next at index 1, and so on, as for array indexing. If the char value specified by the index is a surrogate, the surrogate value is returned. Specified by: charAt(...) in CharSequence Parameters: index the index of the char value. Returns: the char value at the specified index of this string. The first char value is at index 0. Throws: IndexOutOfBoundsException - if the index argument is negative or not less than the length of this string. object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With