1 /*
   2  * Copyright (c) 1994, 2012, 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     /** use serialVersionUID from JDK 1.0.2 for interoperability */
 102     static final long serialVersionUID = 3388685877147921107L;
 103 
 104     /**
 105      * Constructs a string buffer with no characters in it and an
 106      * initial capacity of 16 characters.
 107      */
 108     public StringBuffer() {
 109         super(16);
 110     }
 111 
 112     /**
 113      * Constructs a string buffer with no characters in it and
 114      * the specified initial capacity.
 115      *
 116      * @param      capacity  the initial capacity.
 117      * @exception  NegativeArraySizeException  if the {@code capacity}
 118      *               argument is less than {@code 0}.
 119      */
 120     public StringBuffer(int capacity) {
 121         super(capacity);
 122     }
 123 
 124     /**
 125      * Constructs a string buffer initialized to the contents of the
 126      * specified string. The initial capacity of the string buffer is
 127      * {@code 16} plus the length of the string argument.
 128      *
 129      * @param   str   the initial contents of the buffer.
 130      */
 131     public StringBuffer(String str) {
 132         super(str.length() + 16);
 133         append(str);
 134     }
 135 
 136     /**
 137      * Constructs a string buffer that contains the same characters
 138      * as the specified {@code CharSequence}. The initial capacity of
 139      * the string buffer is {@code 16} plus the length of the
 140      * {@code CharSequence} argument.
 141      * <p>
 142      * If the length of the specified {@code CharSequence} is
 143      * less than or equal to zero, then an empty buffer of capacity
 144      * {@code 16} is returned.
 145      *
 146      * @param      seq   the sequence to copy.
 147      * @since 1.5
 148      */
 149     public StringBuffer(CharSequence seq) {
 150         this(seq.length() + 16);
 151         append(seq);
 152     }
 153 
 154     @Override
 155     public synchronized int length() {
 156         return count;
 157     }
 158 
 159     @Override
 160     public synchronized int capacity() {
 161         return value.length;
 162     }
 163 
 164 
 165     @Override
 166     public synchronized void ensureCapacity(int minimumCapacity) {
 167         if (minimumCapacity > value.length) {
 168             expandCapacity(minimumCapacity);
 169         }
 170     }
 171 
 172     /**
 173      * @since      1.5
 174      */
 175     @Override
 176     public synchronized void trimToSize() {
 177         super.trimToSize();
 178     }
 179 
 180     /**
 181      * @throws IndexOutOfBoundsException {@inheritDoc}
 182      * @see        #length()
 183      */
 184     @Override
 185     public synchronized void setLength(int newLength) {
 186         super.setLength(newLength);
 187     }
 188 
 189     /**
 190      * @throws IndexOutOfBoundsException {@inheritDoc}
 191      * @see        #length()
 192      */
 193     @Override
 194     public synchronized char charAt(int index) {
 195         if ((index < 0) || (index >= count))
 196             throw new StringIndexOutOfBoundsException(index);
 197         return value[index];
 198     }
 199 
 200     /**
 201      * @since      1.5
 202      */
 203     @Override
 204     public synchronized int codePointAt(int index) {
 205         return super.codePointAt(index);
 206     }
 207 
 208     /**
 209      * @since     1.5
 210      */
 211     @Override
 212     public synchronized int codePointBefore(int index) {
 213         return super.codePointBefore(index);
 214     }
 215 
 216     /**
 217      * @since     1.5
 218      */
 219     @Override
 220     public synchronized int codePointCount(int beginIndex, int endIndex) {
 221         return super.codePointCount(beginIndex, endIndex);
 222     }
 223 
 224     /**
 225      * @since     1.5
 226      */
 227     @Override
 228     public synchronized int offsetByCodePoints(int index, int codePointOffset) {
 229         return super.offsetByCodePoints(index, codePointOffset);
 230     }
 231 
 232     /**
 233      * @throws IndexOutOfBoundsException {@inheritDoc}
 234      */
 235     @Override
 236     public synchronized void getChars(int srcBegin, int srcEnd, char[] dst,
 237                                       int dstBegin)
 238     {
 239         super.getChars(srcBegin, srcEnd, dst, dstBegin);
 240     }
 241 
 242     /**
 243      * @throws IndexOutOfBoundsException {@inheritDoc}
 244      * @see        #length()
 245      */
 246     @Override
 247     public synchronized void setCharAt(int index, char ch) {
 248         if ((index < 0) || (index >= count))
 249             throw new StringIndexOutOfBoundsException(index);
 250         value[index] = ch;
 251     }
 252 
 253     @Override
 254     public synchronized StringBuffer append(Object obj) {
 255         super.append(String.valueOf(obj));
 256         return this;
 257     }
 258 
 259     @Override
 260     public synchronized StringBuffer append(String str) {
 261         super.append(str);
 262         return this;
 263     }
 264 
 265     /**
 266      * Appends the specified {@code StringBuffer} to this sequence.
 267      * <p>
 268      * The characters of the {@code StringBuffer} argument are appended,
 269      * in order, to the contents of this {@code StringBuffer}, increasing the
 270      * length of this {@code StringBuffer} by the length of the argument.
 271      * If {@code sb} is {@code null}, then the four characters
 272      * {@code "null"} are appended to this {@code StringBuffer}.
 273      * <p>
 274      * Let <i>n</i> be the length of the old character sequence, the one
 275      * contained in the {@code StringBuffer} just prior to execution of the
 276      * {@code append} method. Then the character at index <i>k</i> in
 277      * the new character sequence is equal to the character at index <i>k</i>
 278      * in the old character sequence, if <i>k</i> is less than <i>n</i>;
 279      * otherwise, it is equal to the character at index <i>k-n</i> in the
 280      * argument {@code sb}.
 281      * <p>
 282      * This method synchronizes on {@code this}, the destination
 283      * object, but does not synchronize on the source ({@code sb}).
 284      *
 285      * @param   sb   the {@code StringBuffer} to append.
 286      * @return  a reference to this object.
 287      * @since 1.4
 288      */
 289     public synchronized StringBuffer append(StringBuffer sb) {
 290         super.append(sb);
 291         return this;
 292     }
 293 
 294     /**
 295      * @since 1.8
 296      */
 297     @Override
 298     synchronized StringBuffer append(AbstractStringBuilder asb) {
 299         super.append(asb);
 300         return this;
 301     }
 302 
 303     /**
 304      * Appends the specified {@code CharSequence} to this
 305      * sequence.
 306      * <p>
 307      * The characters of the {@code CharSequence} argument are appended,
 308      * in order, increasing the length of this sequence by the length of the
 309      * argument.
 310      *
 311      * <p>The result of this method is exactly the same as if it were an
 312      * invocation of this.append(s, 0, s.length());
 313      *
 314      * <p>This method synchronizes on {@code this}, the destination
 315      * object, but does not synchronize on the source ({@code s}).
 316      *
 317      * <p>If {@code s} is {@code null}, then the four characters
 318      * {@code "null"} are appended.
 319      *
 320      * @param   s the {@code CharSequence} to append.
 321      * @return  a reference to this object.
 322      * @since 1.5
 323      */
 324     @Override
 325     public StringBuffer append(CharSequence s) {
 326         // Note, synchronization achieved via invocations of other StringBuffer methods after
 327         // narrowing of s to specific type
 328         super.append(s);
 329         return this;
 330     }
 331 
 332     /**
 333      * @throws IndexOutOfBoundsException {@inheritDoc}
 334      * @since      1.5
 335      */
 336     @Override
 337     public synchronized StringBuffer append(CharSequence s, int start, int end)
 338     {
 339         super.append(s, start, end);
 340         return this;
 341     }
 342 
 343     @Override
 344     public synchronized StringBuffer append(char[] str) {
 345         super.append(str);
 346         return this;
 347     }
 348 
 349     /**
 350      * @throws IndexOutOfBoundsException {@inheritDoc}
 351      */
 352     @Override
 353     public synchronized StringBuffer append(char[] str, int offset, int len) {
 354         super.append(str, offset, len);
 355         return this;
 356     }
 357 
 358     @Override
 359     public synchronized StringBuffer append(boolean b) {
 360         super.append(b);
 361         return this;
 362     }
 363 
 364     @Override
 365     public synchronized StringBuffer append(char c) {
 366         super.append(c);
 367         return this;
 368     }
 369 
 370     @Override
 371     public synchronized StringBuffer append(int i) {
 372         super.append(i);
 373         return this;
 374     }
 375 
 376     /**
 377      * @since 1.5
 378      */
 379     @Override
 380     public synchronized StringBuffer appendCodePoint(int codePoint) {
 381         super.appendCodePoint(codePoint);
 382         return this;
 383     }
 384 
 385     @Override
 386     public synchronized StringBuffer append(long lng) {
 387         super.append(lng);
 388         return this;
 389     }
 390 
 391     @Override
 392     public synchronized StringBuffer append(float f) {
 393         super.append(f);
 394         return this;
 395     }
 396 
 397     @Override
 398     public synchronized StringBuffer append(double d) {
 399         super.append(d);
 400         return this;
 401     }
 402 
 403     /**
 404      * @throws StringIndexOutOfBoundsException {@inheritDoc}
 405      * @since      1.2
 406      */
 407     @Override
 408     public synchronized StringBuffer delete(int start, int end) {
 409         super.delete(start, end);
 410         return this;
 411     }
 412 
 413     /**
 414      * @throws StringIndexOutOfBoundsException {@inheritDoc}
 415      * @since      1.2
 416      */
 417     @Override
 418     public synchronized StringBuffer deleteCharAt(int index) {
 419         super.deleteCharAt(index);
 420         return this;
 421     }
 422 
 423     /**
 424      * @throws StringIndexOutOfBoundsException {@inheritDoc}
 425      * @since      1.2
 426      */
 427     @Override
 428     public synchronized StringBuffer replace(int start, int end, String str) {
 429         super.replace(start, end, str);
 430         return this;
 431     }
 432 
 433     /**
 434      * @throws StringIndexOutOfBoundsException {@inheritDoc}
 435      * @since      1.2
 436      */
 437     @Override
 438     public synchronized String substring(int start) {
 439         return substring(start, count);
 440     }
 441 
 442     /**
 443      * @throws IndexOutOfBoundsException {@inheritDoc}
 444      * @since      1.4
 445      */
 446     @Override
 447     public synchronized CharSequence subSequence(int start, int end) {
 448         return super.substring(start, end);
 449     }
 450 
 451     /**
 452      * @throws StringIndexOutOfBoundsException {@inheritDoc}
 453      * @since      1.2
 454      */
 455     @Override
 456     public synchronized String substring(int start, int end) {
 457         return super.substring(start, end);
 458     }
 459 
 460     /**
 461      * @throws StringIndexOutOfBoundsException {@inheritDoc}
 462      * @since      1.2
 463      */
 464     @Override
 465     public synchronized StringBuffer insert(int index, char[] str, int offset,
 466                                             int len)
 467     {
 468         super.insert(index, str, offset, len);
 469         return this;
 470     }
 471 
 472     /**
 473      * @throws StringIndexOutOfBoundsException {@inheritDoc}
 474      */
 475     @Override
 476     public synchronized StringBuffer insert(int offset, Object obj) {
 477         super.insert(offset, String.valueOf(obj));
 478         return this;
 479     }
 480 
 481     /**
 482      * @throws StringIndexOutOfBoundsException {@inheritDoc}
 483      */
 484     @Override
 485     public synchronized StringBuffer insert(int offset, String str) {
 486         super.insert(offset, str);
 487         return this;
 488     }
 489 
 490     /**
 491      * @throws StringIndexOutOfBoundsException {@inheritDoc}
 492      */
 493     @Override
 494     public synchronized StringBuffer insert(int offset, char[] str) {
 495         super.insert(offset, str);
 496         return this;
 497     }
 498 
 499     /**
 500      * @throws IndexOutOfBoundsException {@inheritDoc}
 501      * @since      1.5
 502      */
 503     @Override
 504     public StringBuffer insert(int dstOffset, CharSequence s) {
 505         // Note, synchronization achieved via invocations of other StringBuffer methods
 506         // after narrowing of s to specific type
 507         super.insert(dstOffset, s);
 508         return this;
 509     }
 510 
 511     /**
 512      * @throws IndexOutOfBoundsException {@inheritDoc}
 513      * @since      1.5
 514      */
 515     @Override
 516     public synchronized StringBuffer insert(int dstOffset, CharSequence s,
 517             int start, int end)
 518     {
 519         super.insert(dstOffset, s, start, end);
 520         return this;
 521     }
 522 
 523     /**
 524      * @throws StringIndexOutOfBoundsException {@inheritDoc}
 525      */
 526     @Override
 527     public  StringBuffer insert(int offset, boolean b) {
 528         // Note, synchronization achieved via invocation of StringBuffer insert(int, String)
 529         // after conversion of b to String by super class method
 530         super.insert(offset, b);
 531         return this;
 532     }
 533 
 534     /**
 535      * @throws IndexOutOfBoundsException {@inheritDoc}
 536      */
 537     @Override
 538     public synchronized StringBuffer insert(int offset, char c) {
 539         super.insert(offset, c);
 540         return this;
 541     }
 542 
 543     /**
 544      * @throws StringIndexOutOfBoundsException {@inheritDoc}
 545      */
 546     @Override
 547     public StringBuffer insert(int offset, int i) {
 548         // Note, synchronization achieved via invocation of StringBuffer insert(int, String)
 549         // after conversion of i to String by super class method
 550         super.insert(offset, i);
 551         return this;
 552     }
 553 
 554     /**
 555      * @throws StringIndexOutOfBoundsException {@inheritDoc}
 556      */
 557     @Override
 558     public StringBuffer insert(int offset, long l) {
 559         // Note, synchronization achieved via invocation of StringBuffer insert(int, String)
 560         // after conversion of l to String by super class method
 561         super.insert(offset, l);
 562         return this;
 563     }
 564 
 565     /**
 566      * @throws StringIndexOutOfBoundsException {@inheritDoc}
 567      */
 568     @Override
 569     public StringBuffer insert(int offset, float f) {
 570         // Note, synchronization achieved via invocation of StringBuffer insert(int, String)
 571         // after conversion of f to String by super class method
 572         super.insert(offset, f);
 573         return this;
 574     }
 575 
 576     /**
 577      * @throws StringIndexOutOfBoundsException {@inheritDoc}
 578      */
 579     @Override
 580     public StringBuffer insert(int offset, double d) {
 581         // Note, synchronization achieved via invocation of StringBuffer insert(int, String)
 582         // after conversion of d to String by super class method
 583         super.insert(offset, d);
 584         return this;
 585     }
 586 
 587     /**
 588      * @since      1.4
 589      */
 590     @Override
 591     public int indexOf(String str) {
 592         // Note, synchronization achieved via invocations of other StringBuffer methods
 593         return super.indexOf(str);
 594     }
 595 
 596     /**
 597      * @since      1.4
 598      */
 599     @Override
 600     public synchronized int indexOf(String str, int fromIndex) {
 601         return super.indexOf(str, fromIndex);
 602     }
 603 
 604     /**
 605      * @since      1.4
 606      */
 607     @Override
 608     public int lastIndexOf(String str) {
 609         // Note, synchronization achieved via invocations of other StringBuffer methods
 610         return lastIndexOf(str, count);
 611     }
 612 
 613     /**
 614      * @since      1.4
 615      */
 616     @Override
 617     public synchronized int lastIndexOf(String str, int fromIndex) {
 618         return super.lastIndexOf(str, fromIndex);
 619     }
 620 
 621     /**
 622      * @since   JDK1.0.2
 623      */
 624     @Override
 625     public synchronized StringBuffer reverse() {
 626         super.reverse();
 627         return this;
 628     }
 629 
 630     @Override
 631     public synchronized String toString() {
 632         return new String(value, 0, count);
 633     }
 634 
 635     /**
 636      * Serializable fields for StringBuffer.
 637      *
 638      * @serialField value  char[]
 639      *              The backing character array of this StringBuffer.
 640      * @serialField count int
 641      *              The number of characters in this StringBuffer.
 642      * @serialField shared  boolean
 643      *              A flag indicating whether the backing array is shared.
 644      *              The value is ignored upon deserialization.
 645      */
 646     private static final java.io.ObjectStreamField[] serialPersistentFields =
 647     {
 648         new java.io.ObjectStreamField("value", char[].class),
 649         new java.io.ObjectStreamField("count", Integer.TYPE),
 650         new java.io.ObjectStreamField("shared", Boolean.TYPE),
 651     };
 652 
 653     /**
 654      * readObject is called to restore the state of the StringBuffer from
 655      * a stream.
 656      */
 657     private synchronized void writeObject(java.io.ObjectOutputStream s)
 658         throws java.io.IOException {
 659         java.io.ObjectOutputStream.PutField fields = s.putFields();
 660         fields.put("value", value);
 661         fields.put("count", count);
 662         fields.put("shared", false);
 663         s.writeFields();
 664     }
 665 
 666     /**
 667      * readObject is called to restore the state of the StringBuffer from
 668      * a stream.
 669      */
 670     private void readObject(java.io.ObjectInputStream s)
 671         throws java.io.IOException, ClassNotFoundException {
 672         java.io.ObjectInputStream.GetField fields = s.readFields();
 673         value = (char[])fields.get("value", null);
 674         count = fields.get("count", 0);
 675     }
 676 }