Learn AP Comp Sci

☰

Problem of the Day

Tuesday, November 10, 2026


Problem:

Java's substring method is typically used to return a subset of the characters in a larger string. If one specifies a start value less than the initial index of 0 or an end value beyond the end of the string, however, a runtime error is thrown: StringIndexOutOfBoundsException.

Consider the static method shown below, intended to eliminate those errors. A starting index before the beginning of the string, rather than throwing an error, will start the substring at the beginning of the string. Likewise, an ending index beyond the end of the string, rather than throwing an error, will end the substring at the end of the string.

/**
* Eliminates bounds errors that occur if substring is called
* with a start or end value beyond the bounds of the string.
* @param str the string we're getting a substring from
* @param start the first position of the substring, inclusive
* @param end the final position of the substring, exclusive
* @return a substring that works without bounds errors
*/
public static String alternateSubstring(String str, int start, int end)
{

/* missing code */

}

Which of the following could be used to replace /* missing code */ so that the method will work as intended?


  1. if (start < 0) { start = 0; }
    if (end > str.length()) { end = str.length(); }
    return str.substring(start, end);

  2. return str.substring(0, str.length());

  3. return str.substring(0, str.length() - 1);

  4. if (start < 0) { start = 0; }
    if (end > str.length()) { end = str.length() - 1; }
    return str.substring(start, end);

Show solution:

The correct answer is a. Values for start and end are adjusted as necessary to ensure that the call to substring will not cause any bounds errors.