Skip to content

Labs

The String method public String substring(int beginIndex, int endIndex) returns a substring of a String instance. Create a new JUnit 5 (JUnit Jupiter) test case for this method, with test methods that:

  1. Test that "abcdefg".substring(1, 5) returns "bcde".
  2. Test that "abcdefg".substring(0, 7) returns "abcdefg".
  3. This method's purpose is to test that beginIndex is inclusive and endIndex is exclusive (note that character 7 is the length() of this String). The method should state this purpose.
  4. Test that substring throws IndexOutOfBoundsException
  5. if the beginIndex is negative.
  6. if endIndex is larger than the length of this String object.
  7. if beginIndex is larger than endIndex.
  8. The String specification says substring throws IndexOutOfBoundsException; this is correct, according to the spec.
  9. Test that the exception thrown by substring is actually StringIndexOutOfBoundsException, a subclass of IndexOutOfBoundsException.
    • Use the methods getClass() and getSimpleName() to get the exception's name.

(Solution: SubstringTests.java)

Practice Exercise

The substring specification is correct because StringIndexOutOfBoundsException IS-A subclass of IndexOutOfBoundsException.

Another JVM may throw IndexOutOfBoundsException - not its subclass - and still comply with the spec.

Therefore, if we are asked what substring throws, we say IndexOutOfBoundsException.


Prev -- Up