Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8151242

Exception thrown by String.substring(int) reports wrong index

XMLWordPrintable

    • generic
    • generic

      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 ----------

            psonal Pallavi Sonal (Inactive)
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved: