JDK-8218228 : The constructor StringBuffer(CharSequence) violates spec for negatively sized argument
  • Type: Bug
  • Component: core-libs
  • Sub-Component: java.lang
  • Priority: P3
  • Status: Closed
  • Resolution: Fixed
  • Submitted: 2019-02-02
  • Updated: 2019-04-03
  • Resolved: 2019-03-01
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 b11Fixed
Related Reports
CSR :  
Relates :  
Sub Tasks
JDK-8218884 :  
Description
The specification states:

"""
If the length of the specified CharSequence is less than or equal to zero, then an empty buffer of capacity 16 is returned.
"""

However, the current implementation throws NegativeArraySizeException instead.

Here's the testcase to demonstrate the issue:

public class U {
    public static void main(String[] args) {
        CharSequence seq = new MyNegLenCharSeq();
        StringBuffer sb = new StringBuffer(seq);
        System.out.println(sb.capacity());
    }

    private static class MyNegLenCharSeq implements CharSequence {
        public char charAt(int i) {
            throw new UnsupportedOperationException();
        }
        public int length() { return -42; }
        public CharSequence subSequence(int st, int e) {
            throw new UnsupportedOperationException();
        }
        public String toString() { return ""; }
    }
}

igerasim@ivirt16:~/work/8218227$ ~/java13/jdk/bin/java -showversion U
java version "13-ea" 2019-09-17
Java(TM) SE Runtime Environment (build 13-ea+6)
Java HotSpot(TM) 64-Bit Server VM (build 13-ea+6, mixed mode, sharing)
Exception in thread "main" java.lang.NegativeArraySizeException: -26
	at java.base/java.lang.AbstractStringBuilder.<init>(AbstractStringBuilder.java:86)
	at java.base/java.lang.StringBuffer.<init>(StringBuffer.java:139)
	at java.base/java.lang.StringBuffer.<init>(StringBuffer.java:169)
	at U.main(U.java:5)

Comments
Currently, the type of the exception thrown with negatively sized argument may be either IndexOutOfBoundsException (if the argument's length is in range [-16, -1]), or NegativeArraySizeException (if the argument's length is less than -16). For consistency, the implementation has to be modified to always throw NegativeArraySizeException.
11-02-2019

This behavior is observed with JDK versions 5, 6, 7, 8, 9, 10, 11, 12, 13. So, it may be better to modify the spec rather than to modify the implementation.
06-02-2019