JDK-8151242 : Exception thrown by String.substring(int) reports wrong index
  • Type: Bug
  • Component: core-libs
  • Sub-Component: java.lang
  • Affected Version: 8u66
  • Priority: P4
  • Status: Closed
  • Resolution: Not an Issue
  • OS: generic
  • CPU: generic
  • Submitted: 2016-03-03
  • Updated: 2019-06-26
  • Resolved: 2016-03-04
Related Reports
Duplicate :  
Description
FULL PRODUCT VERSION :
$ java -version
java version "1.8.0_60"
Java(TM) SE Runtime Environment (build 1.8.0_60-b27)
Java HotSpot(TM) 64-Bit Server VM (build 25.60-b23, mixed mode)

ADDITIONAL OS VERSION INFORMATION :
Darwin localhost.local 15.3.0 Darwin Kernel Version 15.3.0: Thu Dec 10 18:40:58 PST 2015; root:xnu-3248.30.4~1/RELEASE_X86_64 x86_64

A DESCRIPTION OF THE PROBLEM :
When calling

    "foobar".substring(8)

the expectation is that an StringIndexOutOfBoundsException is thrown with the message "String index out of range: 8". Instead an exception with the message "String index out of range: -2" is thrown.

In cases the index asked for is generated, the information in the exception message doesn't help debugging, but instead makes it harder as it is ambivalent.

STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
Call

    "foobar".substring(8)

EXPECTED VERSUS ACTUAL BEHAVIOR :
EXPECTED -
An instance of StringIndexOutOfBoundsException is thrown with the message "String index out of range: 8"
ACTUAL -
An instance of StringIndexOutOfBoundsException is thrown with the message "String index out of range: -2"

REPRODUCIBILITY :
This bug can be reproduced always.

---------- BEGIN SOURCE ----------
        final int wrongIndex = 8;
        final String expectedMessage = "String index out of range: " + wrongIndex;
        String actualMessage;

        try {
            "foobar".substring(wrongIndex);
            actualMessage = "";
        } catch (StringIndexOutOfBoundsException sioobe) {
            actualMessage = sioobe.getMessage();
        }

        System.err.println("Asserting actualMessage (\"" + actualMessage + "\") equals expectedMessage (\"" + expectedMessage + "\"):" );
        assert(actualMessage == expectedMessage);
---------- END SOURCE ----------


Comments
This is not an issue. When the substring method is called on the "foobar" string, the beginIndex is 8 and the endIndex is the length of the string i.e 6. So, the length of substring = endIndex - beginIndex = 6 - 8 = -2 which shows that the beginIndex is out of the bounds.
04-03-2016