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

StringBuffer.repeat does not work correctly after toString() was called

XMLWordPrintable

    • b05
    • generic
    • generic
    • Verified

        A DESCRIPTION OF THE PROBLEM :
        This issue exists for both StringBuffer.repeat(CharSequence cs, int count) and StringBuffer.repeat(int codePoint, int count).

        When the method StringBuffer.repeat(CharSequence cs, int count) is invoked with parameter count >= 2 after toString() method was invoked, it does not append the given character sequence repeatedly to the string buffer as expected. The method StringBuffer.repeat(int codePoint, int count) does not work with any count >= 1 after invocation of toString() either.

        This issue does not occur for StringBuilder.

        STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
        Compile and run this code with JDK version 21.

        EXPECTED VERSUS ACTUAL BEHAVIOR :
        EXPECTED -
        This code should print the following result:

        abb
        abb
        ab
        ACTUAL -
        This code prints the following result:

        a
        a
        a

        ---------- BEGIN SOURCE ----------
        public class Main {
            public static void main(String[] args) {
                test1();
                test2();
                test3();
            }

            private static void test1() {
                var sbf = new StringBuffer("a");
                sbf.toString(); // necessary to produce the bug
                sbf.repeat("b", 2);
                System.out.println(sbf); // implicit toString() call
            }

            private static void test2() {
                var sbf = new StringBuffer("a");
                sbf.toString();
                sbf.repeat('b', 2);
                System.out.println(sbf);
            }

            private static void test3() {
                var sbf = new StringBuffer("a");
                sbf.toString();
                sbf.repeat('b', 1);
                System.out.println(sbf);
            }
        }
        ---------- END SOURCE ----------

        CUSTOMER SUBMITTED WORKAROUND :
        Replace StringBuffer with StringBuilder (since StringBuffer is not widely used in modern Java programming). Or try to invoke toString() only once.

        FREQUENCY : always


              jlaskey Jim Laskey
              webbuggrp Webbug Group
              Votes:
              0 Vote for this issue
              Watchers:
              9 Start watching this issue

                Created:
                Updated:
                Resolved: