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

StringBuilder/StringBuffer constructor throws confusing NegativeArraySizeException

XMLWordPrintable

    • Icon: Bug Bug
    • Resolution: Fixed
    • Icon: P4 P4
    • 13
    • None
    • core-libs
    • None
    • b07

      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.

            igerasim Ivan Gerasimov
            igerasim Ivan Gerasimov
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated:
              Resolved: