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