JDK-8138614 : (spec str) StringBuffer and StringBuilder methods improperly require "new" String to be returned
  • Type: Bug
  • Component: core-libs
  • Sub-Component: java.lang
  • Affected Version: 8,9
  • Priority: P4
  • Status: Resolved
  • Resolution: Fixed
  • Submitted: 2015-09-30
  • Updated: 2025-03-13
  • Resolved: 2025-02-25
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 25
25 b12Fixed
Related Reports
CSR :  
Duplicate :  
Relates :  
Relates :  
Relates :  
Relates :  
Sub Tasks
JDK-8350042 :  
Description
Several methods in StringBuilder and StringBuffer return String objects. Their specifications require creation of new String objects even though this is unnecessary in some circumstances. Such methods include:

  substring(int)
  substring(int, int)
  subSequence(int, int)
  toString()

in both StringBuffer and StringBuilder.

The specs of the corresponding methods in String were clarified by JDK-7174936, and the spec of the CharSequence.subSequence method was clarified by JDK-8028757.

An example where a new String object need not be created might be if the result of calling toString() were cached, so that subsequent calls to toString() might return the same String. Another example would be returning "" (the empty string literal) if a substring has zero length.

The subSequence() method is declared to return CharSequence, but in both StringBuilder and StringBuffer it is specified to behave identically to the substring() method, which returns a String. Thus subSequence() returns a String that has been upcast to CharSequence. Since String objects can be freely reused, the relaxation of the "new" requirement does apply to subSequence(). (It doesn't apply to CharBuffer, though, which specifically requires that it returns a new CharBuffer.)
Comments
If ths spec change JDK-8138614 is ever backported to JDK 21 in a Maintenance Release, then the regression fix JDK-8325730 can also be backported to JDK 21.
13-03-2025

Changeset: 08bc59da Branch: master Author: Stuart Marks <smarks@openjdk.org> Date: 2025-02-25 15:18:30 +0000 URL: https://git.openjdk.org/jdk/commit/08bc59da9b66c6504a2d2712feebf37cc5eb2d3e
25-02-2025

A pull request was submitted for review. Branch: master URL: https://git.openjdk.org/jdk/pull/23599 Date: 2025-02-12 19:55:29 +0000
12-02-2025

See comment here: https://bugs.openjdk.org/browse/JDK-8325730?focusedId=14750130&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-14750130
06-02-2025