1 /*
   2  * Copyright (c) 1994, 2013, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.lang;
  27 
  28 
  29 /**
  30  * A thread-safe, mutable sequence of characters.
  31  * A string buffer is like a {@link String}, but can be modified. At any
  32  * point in time it contains some particular sequence of characters, but
  33  * the length and content of the sequence can be changed through certain
  34  * method calls.
  35  * <p>
  36  * String buffers are safe for use by multiple threads. The methods
  37  * are synchronized where necessary so that all the operations on any
  38  * particular instance behave as if they occur in some serial order
  39  * that is consistent with the order of the method calls made by each of
  40  * the individual threads involved.
  41  * <p>
  42  * The principal operations on a {@code StringBuffer} are the
  43  * {@code append} and {@code insert} methods, which are
  44  * overloaded so as to accept data of any type. Each effectively
  45  * converts a given datum to a string and then appends or inserts the
  46  * characters of that string to the string buffer. The
  47  * {@code append} method always adds these characters at the end
  48  * of the buffer; the {@code insert} method adds the characters at
  49  * a specified point.
  50  * <p>
  51  * For example, if {@code z} refers to a string buffer object
  52  * whose current contents are {@code "start"}, then
  53  * the method call {@code z.append("le")} would cause the string
  54  * buffer to contain {@code "startle"}, whereas
  55  * {@code z.insert(4, "le")} would alter the string buffer to
  56  * contain {@code "starlet"}.
  57  * <p>
  58  * In general, if sb refers to an instance of a {@code StringBuffer},
  59  * then {@code sb.append(x)} has the same effect as
  60  * {@code sb.insert(sb.length(), x)}.
  61  * <p>
  62  * Whenever an operation occurs involving a source sequence (such as
  63  * appending or inserting from a source sequence), this class synchronizes
  64  * only on the string buffer performing the operation, not on the source.
  65  * Note that while {@code StringBuffer} is designed to be safe to use
  66  * concurrently from multiple threads, if the constructor or the
  67  * {@code append} or {@code insert} operation is passed a source sequence
  68  * that is shared across threads, the calling code must ensure
  69  * that the operation has a consistent and unchanging view of the source
  70  * sequence for the duration of the operation.
  71  * This could be satisfied by the caller holding a lock during the
  72  * operation's call, by using an immutable source sequence, or by not
  73  * sharing the source sequence across threads.
  74  * <p>
  75  * Every string buffer has a capacity. As long as the length of the
  76  * character sequence contained in the string buffer does not exceed
  77  * the capacity, it is not necessary to allocate a new internal
  78  * buffer array. If the internal buffer overflows, it is
  79  * automatically made larger.
  80  * <p>
  81  * Unless otherwise noted, passing a {@code null} argument to a constructor
  82  * or method in this class will cause a {@link NullPointerException} to be
  83  * thrown.
  84  * <p>
  85  * As of  release JDK 5, this class has been supplemented with an equivalent
  86  * class designed for use by a single thread, {@link StringBuilder}.  The
  87  * {@code StringBuilder} class should generally be used in preference to
  88  * this one, as it supports all of the same operations but it is faster, as
  89  * it performs no synchronization.
  90  *
  91  * @author      Arthur van Hoff
  92  * @see     java.lang.StringBuilder
  93  * @see     java.lang.String
  94  * @since   JDK1.0
  95  */
  96  public final class StringBuffer
  97     extends AbstractStringBuilder
  98     implements java.io.Serializable, CharSequence
  99 {
 100 
 101     /**
 102      * A cache of the last value returned by toString. Cleared
 103      * whenever the StringBuffer is modified.
 104      */
 105     private transient String toStringCache;
 106 
 107     /** use serialVersionUID from JDK 1.0.2 for interoperability */
 108     static final long serialVersionUID = 3388685877147921107L;
 109 
 110     /**
 111      * Constructs a string buffer with no characters in it and an
 112      * initial capacity of 16 characters.
 113      */
 114     public StringBuffer() {
 115         super(16);
 116     }
 117 
 118     /**
 119      * Constructs a string buffer with no characters in it and
 120      * the specified initial capacity.
 121      *
 122      * @param      capacity  the initial capacity.
 123      * @exception  NegativeArraySizeException  if the {@code capacity}
 124      *               argument is less than {@code 0}.
 125      */
 126     public StringBuffer(int capacity) {
 127         super(capacity);
 128     }
 129 
 130     /**
 131      * Constructs a string buffer initialized to the contents of the
 132      * specified string. The initial capacity of the string buffer is
 133      * {@code 16} plus the length of the string argument.
 134      *
 135      * @param   str   the initial contents of the buffer.
 136      */
 137     public StringBuffer(String str) {
 138         super(str.length() + 16);
 139         append(str);
 140     }
 141 
 142     /**
 143      * Constructs a string buffer that contains the same characters
 144      * as the specified {@code CharSequence}. The initial capacity of
 145      * the string buffer is {@code 16} plus the length of the
 146      * {@code CharSequence} argument.
 147      * <p>
 148      * If the length of the specified {@code CharSequence} is
 149      * less than or equal to zero, then an empty buffer of capacity
 150      * {@code 16} is returned.
 151      *
 152      * @param      seq   the sequence to copy.
 153      * @since 1.5
 154      */
 155     public StringBuffer(CharSequence seq) {
 156         this(seq.length() + 16);
 157         append(seq);
 158     }
 159 
 160     @Override
 161     public synchronized int length() {
 162         return count;
 163     }
 164 
 165     @Override
 166     public synchronized int capacity() {
 167         return value.length;
 168     }
 169 
 170 
 171     @Override
 172     public synchronized void ensureCapacity(int minimumCapacity) {
 173         if (minimumCapacity > value.length) {
 174             expandCapacity(minimumCapacity);
 175         }
 176     }
 177 
 178     /**
 179      * @since      1.5
 180      */
 181     @Override
 182     public synchronized void trimToSize() {
 183         super.trimToSize();
 184     }
 185 
 186     /**
 187      * @throws IndexOutOfBoundsException {@inheritDoc}
 188      * @see        #length()
 189      */
 190     @Override
 191     public synchronized void setLength(int newLength) {
 192         super.setLength(newLength);
 193         toStringCache = null;
 194     }
 195 
 196     /**
 197      * @throws IndexOutOfBoundsException {@inheritDoc}
 198      * @see        #length()
 199      */
 200     @Override
 201     public synchronized char charAt(int index) {
 202         if ((index < 0) || (index >= count))
 203             throw new StringIndexOutOfBoundsException(index);
 204         return value[index];
 205     }
 206 
 207     /**
 208      * @since      1.5
 209      */
 210     @Override
 211     public synchronized int codePointAt(int index) {
 212         return super.codePointAt(index);
 213     }
 214 
 215     /**
 216      * @since     1.5
 217      */
 218     @Override
 219     public synchronized int codePointBefore(int index) {
 220         return super.codePointBefore(index);
 221     }
 222 
 223     /**
 224      * @since     1.5
 225      */
 226     @Override
 227     public synchronized int codePointCount(int beginIndex, int endIndex) {
 228         return super.codePointCount(beginIndex, endIndex);
 229     }
 230 
 231     /**
 232      * @since     1.5
 233      */
 234     @Override
 235     public synchronized int offsetByCodePoints(int index, int codePointOffset) {
 236         return super.offsetByCodePoints(index, codePointOffset);
 237     }
 238 
 239     /**
 240      * @throws IndexOutOfBoundsException {@inheritDoc}
 241      */
 242     @Override
 243     public synchronized void getChars(int srcBegin, int srcEnd, char[] dst,
 244                                       int dstBegin)
 245     {
 246         super.getChars(srcBegin, srcEnd, dst, dstBegin);
 247     }
 248 
 249     /**
 250      * @throws IndexOutOfBoundsException {@inheritDoc}
 251      * @see        #length()
 252      */
 253     @Override
 254     public synchronized void setCharAt(int index, char ch) {
 255         if ((index < 0) || (index >= count))
 256             throw new StringIndexOutOfBoundsException(index);
 257         value[index] = ch;
 258         toStringCache = null;
 259     }
 260 
 261     @Override
 262     public synchronized StringBuffer append(Object obj) {
 263         super.append(String.valueOf(obj));
 264         toStringCache = null;
 265         return this;
 266     }
 267 
 268     @Override
 269     public synchronized StringBuffer append(String str) {
 270         super.append(str);
 271         toStringCache = null;
 272         return this;
 273     }
 274 
 275     /**
 276      * Appends the specified {@code StringBuffer} to this sequence.
 277      * <p>
 278      * The characters of the {@code StringBuffer} argument are appended,
 279      * in order, to the contents of this {@code StringBuffer}, increasing the
 280      * length of this {@code StringBuffer} by the length of the argument.
 281      * If {@code sb} is {@code null}, then the four characters
 282      * {@code "null"} are appended to this {@code StringBuffer}.
 283      * <p>
 284      * Let <i>n</i> be the length of the old character sequence, the one
 285      * contained in the {@code StringBuffer} just prior to execution of the
 286      * {@code append} method. Then the character at index <i>k</i> in
 287      * the new character sequence is equal to the character at index <i>k</i>
 288      * in the old character sequence, if <i>k</i> is less than <i>n</i>;
 289      * otherwise, it is equal to the character at index <i>k-n</i> in the
 290      * argument {@code sb}.
 291      * <p>
 292      * This method synchronizes on {@code this}, the destination
 293      * object, but does not synchronize on the source ({@code sb}).
 294      *
 295      * @param   sb   the {@code StringBuffer} to append.
 296      * @return  a reference to this object.
 297      * @since 1.4
 298      */
 299     public synchronized StringBuffer append(StringBuffer sb) {
 300         super.append(sb);
 301         toStringCache = null;
 302         return this;
 303     }
 304 
 305     /**
 306      * @since 1.8
 307      */
 308     @Override
 309     synchronized StringBuffer append(AbstractStringBuilder asb) {
 310         super.append(asb);
 311         toStringCache = null;
 312         return this;
 313     }
 314 
 315     /**
 316      * Appends the specified {@code CharSequence} to this
 317      * sequence.
 318      * <p>
 319      * The characters of the {@code CharSequence} argument are appended,
 320      * in order, increasing the length of this sequence by the length of the
 321      * argument.
 322      *
 323      * <p>The result of this method is exactly the same as if it were an
 324      * invocation of this.append(s, 0, s.length());
 325      *
 326      * <p>This method synchronizes on {@code this}, the destination
 327      * object, but does not synchronize on the source ({@code s}).
 328      *
 329      * <p>If {@code s} is {@code null}, then the four characters
 330      * {@code "null"} are appended.
 331      *
 332      * @param   s the {@code CharSequence} to append.
 333      * @return  a reference to this object.
 334      * @since 1.5
 335      */
 336     @Override
 337     public StringBuffer append(CharSequence s) {
 338         // Note, synchronization achieved via invocations of other StringBuffer methods after
 339         // narrowing of s to specific type
 340         // Ditto for toStringCache clearing
 341         super.append(s);
 342         return this;
 343     }
 344 
 345     /**
 346      * @throws IndexOutOfBoundsException {@inheritDoc}
 347      * @since      1.5
 348      */
 349     @Override
 350     public synchronized StringBuffer append(CharSequence s, int start, int end)
 351     {
 352         super.append(s, start, end);
 353         toStringCache = null;
 354         return this;
 355     }
 356 
 357     @Override
 358     public synchronized StringBuffer append(char[] str) {
 359         super.append(str);
 360         toStringCache = null;
 361         return this;
 362     }
 363 
 364     /**
 365      * @throws IndexOutOfBoundsException {@inheritDoc}
 366      */
 367     @Override
 368     public synchronized StringBuffer append(char[] str, int offset, int len) {
 369         super.append(str, offset, len);
 370         toStringCache = null;
 371         return this;
 372     }
 373 
 374     @Override
 375     public synchronized StringBuffer append(boolean b) {
 376         super.append(b);
 377         toStringCache = null;
 378         return this;
 379     }
 380 
 381     @Override
 382     public synchronized StringBuffer append(char c) {
 383         super.append(c);
 384         toStringCache = null;
 385         return this;
 386     }
 387 
 388     @Override
 389     public synchronized StringBuffer append(int i) {
 390         super.append(i);
 391         toStringCache = null;
 392         return this;
 393     }
 394 
 395     /**
 396      * @since 1.5
 397      */
 398     @Override
 399     public synchronized StringBuffer appendCodePoint(int codePoint) {
 400         super.appendCodePoint(codePoint);
 401         toStringCache = null;
 402         return this;
 403     }
 404 
 405     @Override
 406     public synchronized StringBuffer append(long lng) {
 407         super.append(lng);
 408         toStringCache = null;
 409         return this;
 410     }
 411 
 412     @Override
 413     public synchronized StringBuffer append(float f) {
 414         super.append(f);
 415         toStringCache = null;
 416         return this;
 417     }
 418 
 419     @Override
 420     public synchronized StringBuffer append(double d) {
 421         super.append(d);
 422         toStringCache = null;
 423         return this;
 424     }
 425 
 426     /**
 427      * @throws StringIndexOutOfBoundsException {@inheritDoc}
 428      * @since      1.2
 429      */
 430     @Override
 431     public synchronized StringBuffer delete(int start, int end) {
 432         super.delete(start, end);
 433         toStringCache = null;
 434         return this;
 435     }
 436 
 437     /**
 438      * @throws StringIndexOutOfBoundsException {@inheritDoc}
 439      * @since      1.2
 440      */
 441     @Override
 442     public synchronized StringBuffer deleteCharAt(int index) {
 443         super.deleteCharAt(index);
 444         toStringCache = null;
 445         return this;
 446     }
 447 
 448     /**
 449      * @throws StringIndexOutOfBoundsException {@inheritDoc}
 450      * @since      1.2
 451      */
 452     @Override
 453     public synchronized StringBuffer replace(int start, int end, String str) {
 454         super.replace(start, end, str);
 455         toStringCache = null;
 456         return this;
 457     }
 458 
 459     /**
 460      * @throws StringIndexOutOfBoundsException {@inheritDoc}
 461      * @since      1.2
 462      */
 463     @Override
 464     public synchronized String substring(int start) {
 465         return substring(start, count);
 466     }
 467 
 468     /**
 469      * @throws IndexOutOfBoundsException {@inheritDoc}
 470      * @since      1.4
 471      */
 472     @Override
 473     public synchronized CharSequence subSequence(int start, int end) {
 474         return super.substring(start, end);
 475     }
 476 
 477     /**
 478      * @throws StringIndexOutOfBoundsException {@inheritDoc}
 479      * @since      1.2
 480      */
 481     @Override
 482     public synchronized String substring(int start, int end) {
 483         return super.substring(start, end);
 484     }
 485 
 486     /**
 487      * @throws StringIndexOutOfBoundsException {@inheritDoc}
 488      * @since      1.2
 489      */
 490     @Override
 491     public synchronized StringBuffer insert(int index, char[] str, int offset,
 492                                             int len)
 493     {
 494         super.insert(index, str, offset, len);
 495         toStringCache = null;
 496         return this;
 497     }
 498 
 499     /**
 500      * @throws StringIndexOutOfBoundsException {@inheritDoc}
 501      */
 502     @Override
 503     public synchronized StringBuffer insert(int offset, Object obj) {
 504         super.insert(offset, String.valueOf(obj));
 505         toStringCache = null;
 506         return this;
 507     }
 508 
 509     /**
 510      * @throws StringIndexOutOfBoundsException {@inheritDoc}
 511      */
 512     @Override
 513     public synchronized StringBuffer insert(int offset, String str) {
 514         super.insert(offset, str);
 515         toStringCache = null;
 516         return this;
 517     }
 518 
 519     /**
 520      * @throws StringIndexOutOfBoundsException {@inheritDoc}
 521      */
 522     @Override
 523     public synchronized StringBuffer insert(int offset, char[] str) {
 524         super.insert(offset, str);
 525         toStringCache = null;
 526         return this;
 527     }
 528 
 529     /**
 530      * @throws IndexOutOfBoundsException {@inheritDoc}
 531      * @since      1.5
 532      */
 533     @Override
 534     public StringBuffer insert(int dstOffset, CharSequence s) {
 535         // Note, synchronization achieved via invocations of other StringBuffer methods
 536         // after narrowing of s to specific type
 537         // Ditto for toStringCache clearing
 538         super.insert(dstOffset, s);
 539         return this;
 540     }
 541 
 542     /**
 543      * @throws IndexOutOfBoundsException {@inheritDoc}
 544      * @since      1.5
 545      */
 546     @Override
 547     public synchronized StringBuffer insert(int dstOffset, CharSequence s,
 548             int start, int end)
 549     {
 550         super.insert(dstOffset, s, start, end);
 551         toStringCache = null;
 552         return this;
 553     }
 554 
 555     /**
 556      * @throws StringIndexOutOfBoundsException {@inheritDoc}
 557      */
 558     @Override
 559     public  StringBuffer insert(int offset, boolean b) {
 560         // Note, synchronization achieved via invocation of StringBuffer insert(int, String)
 561         // after conversion of b to String by super class method
 562         // Ditto for toStringCache clearing
 563         super.insert(offset, b);
 564         return this;
 565     }
 566 
 567     /**
 568      * @throws IndexOutOfBoundsException {@inheritDoc}
 569      */
 570     @Override
 571     public synchronized StringBuffer insert(int offset, char c) {
 572         super.insert(offset, c);
 573         toStringCache = null;
 574         return this;
 575     }
 576 
 577     /**
 578      * @throws StringIndexOutOfBoundsException {@inheritDoc}
 579      */
 580     @Override
 581     public StringBuffer insert(int offset, int i) {
 582         // Note, synchronization achieved via invocation of StringBuffer insert(int, String)
 583         // after conversion of i to String by super class method
 584         // Ditto for toStringCache clearing
 585         super.insert(offset, i);
 586         return this;
 587     }
 588 
 589     /**
 590      * @throws StringIndexOutOfBoundsException {@inheritDoc}
 591      */
 592     @Override
 593     public StringBuffer insert(int offset, long l) {
 594         // Note, synchronization achieved via invocation of StringBuffer insert(int, String)
 595         // after conversion of l to String by super class method
 596         // Ditto for toStringCache clearing
 597         super.insert(offset, l);
 598         return this;
 599     }
 600 
 601     /**
 602      * @throws StringIndexOutOfBoundsException {@inheritDoc}
 603      */
 604     @Override
 605     public StringBuffer insert(int offset, float f) {
 606         // Note, synchronization achieved via invocation of StringBuffer insert(int, String)
 607         // after conversion of f to String by super class method
 608         // Ditto for toStringCache clearing
 609         super.insert(offset, f);
 610         return this;
 611     }
 612 
 613     /**
 614      * @throws StringIndexOutOfBoundsException {@inheritDoc}
 615      */
 616     @Override
 617     public StringBuffer insert(int offset, double d) {
 618         // Note, synchronization achieved via invocation of StringBuffer insert(int, String)
 619         // after conversion of d to String by super class method
 620         // Ditto for toStringCache clearing
 621         super.insert(offset, d);
 622         return this;
 623     }
 624 
 625     /**
 626      * @since      1.4
 627      */
 628     @Override
 629     public int indexOf(String str) {
 630         // Note, synchronization achieved via invocations of other StringBuffer methods
 631         return super.indexOf(str);
 632     }
 633 
 634     /**
 635      * @since      1.4
 636      */
 637     @Override
 638     public synchronized int indexOf(String str, int fromIndex) {
 639         return super.indexOf(str, fromIndex);
 640     }
 641 
 642     /**
 643      * @since      1.4
 644      */
 645     @Override
 646     public int lastIndexOf(String str) {
 647         // Note, synchronization achieved via invocations of other StringBuffer methods
 648         return lastIndexOf(str, count);
 649     }
 650 
 651     /**
 652      * @since      1.4
 653      */
 654     @Override
 655     public synchronized int lastIndexOf(String str, int fromIndex) {
 656         return super.lastIndexOf(str, fromIndex);
 657     }
 658 
 659     /**
 660      * @since   JDK1.0.2
 661      */
 662     @Override
 663     public synchronized StringBuffer reverse() {
 664         super.reverse();
 665         toStringCache = null;
 666         return this;
 667     }
 668 
 669     @Override
 670     public synchronized String toString() {
 671         if (toStringCache == null) {
 672             toStringCache = new String(value, 0, count);
 673             return toStringCache;
 674         } else {
 675             return new String(toStringCache);
 676         }
 677     }
 678 
 679     /**
 680      * Serializable fields for StringBuffer.
 681      *
 682      * @serialField value  char[]
 683      *              The backing character array of this StringBuffer.
 684      * @serialField count int
 685      *              The number of characters in this StringBuffer.
 686      * @serialField shared  boolean
 687      *              A flag indicating whether the backing array is shared.
 688      *              The value is ignored upon deserialization.
 689      */
 690     private static final java.io.ObjectStreamField[] serialPersistentFields =
 691     {
 692         new java.io.ObjectStreamField("value", char[].class),
 693         new java.io.ObjectStreamField("count", Integer.TYPE),
 694         new java.io.ObjectStreamField("shared", Boolean.TYPE),
 695     };
 696 
 697     /**
 698      * readObject is called to restore the state of the StringBuffer from
 699      * a stream.
 700      */
 701     private synchronized void writeObject(java.io.ObjectOutputStream s)
 702         throws java.io.IOException {
 703         java.io.ObjectOutputStream.PutField fields = s.putFields();
 704         fields.put("value", value);
 705         fields.put("count", count);
 706         fields.put("shared", false);
 707         s.writeFields();
 708     }
 709 
 710     /**
 711      * readObject is called to restore the state of the StringBuffer from
 712      * a stream.
 713      */
 714     private void readObject(java.io.ObjectInputStream s)
 715         throws java.io.IOException, ClassNotFoundException {
 716         java.io.ObjectInputStream.GetField fields = s.readFields();
 717         value = (char[])fields.get("value", null);
 718         count = fields.get("count", 0);
 719     }
 720 }