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

StringBuilder/StringBuffer constructor throws confusing NegativeArraySizeException

    XMLWordPrintable

    Details

    • Type: Bug
    • Status: Resolved
    • Priority: P4
    • Resolution: Fixed
    • Affects Version/s: None
    • Fix Version/s: 13
    • Component/s: core-libs
    • Labels:
      None
    • Subcomponent:
    • Resolved In Build:
      b07

      Description

      Two StringBuilder​ constructors that take String or CharSequence argument throw a confusing NegativeArraySizeException if the argument is extremely large.

      This is because the constructor tries to set the initial capacity equal to the length of the argument + 16 (this is specified in the spec, actually).
      When the argument's length is > (Integer.MAX_VALUE - 16), the initial capacity becomes negative due to the integer overflow.

      public class T {
          public static void main(String[] args) {
              // 0, 1 -> cannot create str
              // 2, ..., 15 -> confising NegativeArraySizeException
              // 16, 17 -> OOM in StringBuilder
              // 18 and more -> Ok
              int DELTA = 10;

              String str = "Z".repeat(Integer.MAX_VALUE - DELTA);
              StringBuilder sb = new StringBuilder(str);
          }
      }

      It would be more accurate to throw OutOfMemoryError in such cases.

        Attachments

          Issue Links

            Activity

              People

              Assignee:
              igerasim Ivan Gerasimov
              Reporter:
              igerasim Ivan Gerasimov
              Votes:
              0 Vote for this issue
              Watchers:
              2 Start watching this issue

                Dates

                Created:
                Updated:
                Resolved: