JDK-8218227 : StringBuilder/StringBuffer constructor throws confusing NegativeArraySizeException
  • Type: Bug
  • Component: core-libs
  • Sub-Component: java.lang
  • Priority: P4
  • Status: Resolved
  • Resolution: Fixed
  • Submitted: 2019-02-02
  • Updated: 2022-10-07
  • Resolved: 2019-02-06
The Version table provides details related to the release that this issue/RFE will be addressed.

Unresolved : Release in which this issue/RFE will be addressed.
Resolved: Release in which this issue/RFE has been resolved.
Fixed : Release in which this issue/RFE has been fixed. The release containing this fix may be available for download as an Early Access Release or a General Availability Release.

To download the current JDK release, click here.
JDK 13
13 b07Fixed
Related Reports
Duplicate :  
Relates :  
Relates :  
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.
Comments
[11u hint] I backported follow-up 8249694, but only partially. this applies clean and works fine, but I think fiddling with exceptions is not necessarily needed in 11 at this point.
07-10-2022

Git URL: https://github.com/openjdk/jdk17u/commit/076d2267b6684fc61f1a1922188e5bc80adb768d
07-10-2022

URL: http://hg.openjdk.java.net/jdk/jdk/rev/868611f0adc3 User: igerasim Date: 2019-02-06 01:06:16 +0000
06-02-2019

StringBuffer has the same issue
02-02-2019