The Wayback Machine - https://web.archive.org/web/20200418073614/https://www.geeksforgeeks.org/stringbuffer-class-in-java/amp/

StringBuffer class in Java

String Class in Java

StringBuffer is a peer class of String that provides much of the functionality of strings. String represents fixed-length, immutable character sequences while StringBuffer represents growable and writable character sequences.

StringBuffer may have characters and substrings inserted in the middle or appended to the end. It will automatically grow to make room for such additions and often has more characters preallocated than are actually needed, to allow room for growth.



StringBuffer Constructors

StringBuffer( ): It reserves room for 16 characters without reallocation.

StringBuffer s=new StringBuffer();

StringBuffer( int size)It accepts an integer argument that explicitly sets the size of the buffer.

StringBuffer s=new StringBuffer(20);

StringBuffer(String str): It accepts a String argument that sets the initial contents of the StringBuffer object and reserves room for 16 more characters without reallocation.

StringBuffer s=new StringBuffer("GeeksforGeeks");

Methods

Some of the most used methods are:

 Some Interesting facts:

  1. java.lang.StringBuffer extends (or inherits from) Object class.
  1. All Implemented Interfaces of StringBuffer class:Serializable, Appendable, CharSequence.
  1. public final class StringBuffer extends Object implements Serializable, CharSequence, Appendable
  1. String buffers are safe for use by multiple threads. The methods can be synchronized wherever necessary so that all the operations on any particular instance behave as if they occur in some serial order.
  1. Whenever an operation occurs involving a source sequence (such as appending or inserting from a source sequence) this class synchronizes only on the string buffer performing the operation, not on the source.
  1. It inherits some of the methods from Object class which are clone, equals, finalize, getClass, hashCode, notify, notifyAll.

 StringBuilder: J2SE 5 adds a new string class to Java’s already powerful string handling capabilities. This new class is called StringBuilder. It is identical to StringBuffer except for one important difference: it is not synchronized, which means that it is not thread-safe. The advantage of StringBuilder is faster performance. However, in cases in which you are using multithreading,  you must use StringBuffer rather than StringBuilder.

This article is contributed by Lokesh Todwal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above





Improved By : ShreyasWaghmare

Article Tags :
Practice Tags :