JDK-8332282 : AbstractStringBuilder.toString spec needs amendments for empty strings
  • Type: Enhancement
  • Component: core-libs
  • Sub-Component: java.lang
  • Priority: P4
  • Status: Closed
  • Resolution: Duplicate
  • Submitted: 2024-05-15
  • Updated: 2025-02-10
  • Resolved: 2025-02-10
Related Reports
Duplicate :  
Relates :  
Relates :  
Relates :  
Relates :  
Description
Noticed this when backporting JDK-8325730. There is a seemingly long-standing disconnect between the specification of AbstractStringBuilder.toString:

```
    /**
     * Returns a string representing the data in this sequence.
     * A new {@code String} object is allocated and initialized to
     * contain the character sequence currently represented by this
     * object. This {@code String} is then returned. Subsequent
     * changes to this sequence do not affect the contents of the
     * {@code String}.
     *
     * @return a string representation of this sequence of characters.
     */
    @Override
    public abstract String toString();
```

I read it as: a new string is _always_ allocated with `toString()`.

But this behavior was subtly changed with JDK-8240094 (JDK 15) that started to return the same "" literal string for empty state. JDK-8282429 (JDK 19) "regressed" it back to conformant behavior. JDK-8325730 (JDK 23, backported to JDK 22) regressed the "regression" by starting to return "" again, which again put us into non-spec behavior.

We need to decide which way we should go. Seeing that there are no customer reports about reliance on this behavior, and that nothing, including the tests, have noticed the compatibility problem here, maybe we should just update the spec.
Comments
Closed this one as duplicate of JDK-8138614.
10-02-2025

[~shade] See also JDK-8138614. I'd support an even more relaxed specification which simply requires returning a string with the correct contents, not a "new" string, and not making a special case for the empty string. I made similar changes to the String spec some time ago but I forgot to follow on with StringBuilder/StringBuffer....
06-02-2025