javaexception

String out of bounds exception is not thrown when it should


ALL,

String test = new String[10];
StringBuilder sb = new StringBuilder;

sb.append( test[8].substring( 0, 5 ) );

The test variable will be clearly out of bounds when calling substring, right? And so it should throw the exception....

Thank you.

P.S.: I can't post the actual code - its proprietary and it will be security violation. Sorry. However, the code I posted is close enough..


Solution

  • The test variable will be clearly out of bounds when calling substring, right?

    You are creating an array of 10 String elements, and then you are accessing the 9th element of that array. That is within the array's valid bounds.

    Then, you are calling substring() on the 9th String. However, as all of the Strings have been initialized with null values, it should throw a NullPointerException when trying to calling substring().

    But, even if the Strings had been initialized with empty values ("") instead of null values, you are specifying an endIndex value that is greater than the length of the String, so it should raise an IndexOutOfBoundsException, per the documentation:

    Throws:
    IndexOutOfBoundsException - if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex.