public final class StringBuffer
extends Object
implements SerializableCharSequence

  • Like String class, StringBuffer is another class specifically used to represent and manipulate strings and which can be modified.
  • That means at any point in time it contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls.
  • StringBuffer class is thread-safe i.e. multiple threads cannot access it simultaneously, So it is safe and will result in an order.

  • StringBuffer defines following constructors, 1.StringBuffer():creates an empty string buffer with the initial capacity of 16.
    2.StringBuffer(String str): creates a string buffer with the specified string.
    3.StringBuffer(int capacity): creates an empty string buffer with the specified capacity as length.
    Example: difference between String and StringBuffer


    Reason:
    Output is such because String objects are immutable objects. Hence, if we concatenate on the same String object, it won't be changed (Output: Java). But StringBuffer creates mutable objects. Hence, it can be changed(Output: JavaRace). Important methods of StringBuffer class
    The following methods are some most commonly used methods of StringBuffer class.
    append()
    This method will concatenate the string representation of any type of data to the end of the invoking StringBuffer object. append() method has several overloaded forms.


    The string representation of each parameter is appended to StringBuffer object.


    insert()
    This method inserts one string into another. Here are few forms of insert() method.


    Here the first parameter gives the index at which position the string will be inserted and string representation of second parameter is inserted into StringBuffer object.




    Output : Java12345

    reverse()
    This method reverses the characters within a StringBuffer object.


    Output : ecaRavaJ
    replace()
    This method replaces the string from specified start index to the end index.


    Output : Hello java
      capacity()
    This method returns the current capacity of StringBuffer object.


    Output : 16

    Note: Empty constructor reserves space for 16 characters. Therefore the output is 16.

    ensureCapacity()
    This method is used to ensure minimum capacity of StringBuffer object.
    If the argument of the ensureCapacity() method is less than the existing capacity, then there will be no change in existing capacity.
    If the argument of the ensureCapacity() method is greater than the existing capacity, then there will be change in the current capacity using following rule: newCapacity = (currentCapacity*2) + 2.
Our Services:

Java Training | Python Training | Machine Learning with Python Training | Deep Learning with Python Training | Projects

SILAN Technology
Call to: 9439202111  |  9658317757  |  0674-2361252

Comment