Skip to main content

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:

  • length( ) and capacity( ): The length of a StringBuffer can be found by the length( ) method, while the total allocated capacity can be found by the capacity( ) method.

    Code Example:

    filter_none

    edit

    play_arrow

    brightness_4

    import java.io.*;
    class GFG {
        public static void main(String[] args)
        {
            StringBuffer s = new StringBuffer("GeeksforGeeks");
            int p = s.length();
            int q = s.capacity();
            System.out.println("Length of string GeeksforGeeks=" + p);
            System.out.println("Capacity of string GeeksforGeeks=" + q);
        }
    }
    Output:
    Length of string GeeksforGeeks=13
    Capacity of string GeeksforGeeks=29
    
  • append( )It is used to add text at the end of the existence text. Here are a few of its forms:
    StringBuffer append(String str)
    StringBuffer append(int num)
    

    Code Example:

    filter_none

    edit

    play_arrow

    brightness_4

    import java.io.*;
    class GFG {
        public static void main(String[] args)
        {
            StringBuffer s = new StringBuffer("Geeksfor");
            s.append("Geeks");
            System.out.println(s); // returns GeeksforGeeks
            s.append(1);
            System.out.println(s); // returns GeeksforGeeks1
        }
    }
    Output:

    GeeksforGeeks
    GeeksforGeeks1
    
  • insert( )It is used to insert text at the specified index position. These are a few of its forms:
    StringBuffer insert(int index, String str)
    StringBuffer insert(int index, char ch)

    Here, index specifies the index at which point the string will be inserted into the invoking StringBuffer object.

    Code Example:

    filter_none

    edit

    play_arrow

    brightness_4

    import java.io.*;
    class GFG {
        public static void main(String[] args)
        {
            StringBuffer s = new StringBuffer("GeeksGeeks");
            s.insert(5, "for");
            System.out.println(s); // returns GeeksforGeeks
      
            s.insert(0, 5);
            System.out.println(s); // returns 5GeeksforGeeks
      
            s.insert(3, true);
            System.out.println(s); // returns 5GetrueeksforGeeks
      
            s.insert(5, 41.35d);
            System.out.println(s); // returns 5Getr41.35ueeksforGeeks
      
            s.insert(8, 41.35f);
            System.out.println(s); // returns 5Getr41.41.3535ueeksforGeeks
      
            char geeks_arr[] = { 'p', 'a', 'w', 'a', 'n' };
      
            // insert character array at offset 9
            s.insert(2, geeks_arr);
            System.out.println(s); // returns 5Gpawanetr41.41.3535ueeksforGeeks
        }
    }
    Output:
    GeeksforGeeks
    5GeeksforGeeks
    5GetrueeksforGeeks
    5Getr41.35ueeksforGeeks
    5Getr41.41.3535ueeksforGeeks
    5Gpawanetr41.41.3535ueeksforGeeks
    
  • reverse( )It can reverse the characters within a StringBuffer object using reverse( ).This method returns the reversed object on which it was called. 

    Code Example:

    filter_none

    edit

    play_arrow

    brightness_4

    import java.io.*;
    class GFG {
        public static void main(String[] args)
        {
            StringBuffer s = new StringBuffer("GeeksGeeks");
            s.reverse();
            System.out.println(s); // returns skeeGrofskeeG
        }
    }
    Output:
    skeeGskeeG
    
  • delete( ) and deleteCharAt( )It can delete characters within a StringBuffer by using the methods delete( ) and deleteCharAt( ).The delete( ) method deletes a sequence of characters from the invoking object. Here, start Index specifies the index of the first character to remove, and end Index specifies an index one past the last character to remove. Thus, the substring deleted runs from start Index to endIndex–1. The resulting StringBuffer object is returned. The   deleteCharAt( ) method deletes the character at the index specified by loc. It returns the resulting StringBuffer object.These methods are shown here:
    StringBuffer delete(int startIndex, int endIndex)
    StringBuffer deleteCharAt(int loc)
    

    Code Example:

    filter_none

    edit

    play_arrow

    brightness_4

    import java.io.*;
    class GFG {
        public static void main(String[] args)
        {
            StringBuffer s = new StringBuffer("GeeksforGeeks");
            s.delete(0, 5);
            System.out.println(s); // returns forGeeks
            s.deleteCharAt(7);
            System.out.println(s); // returns forGeek
        }
    }
    Output:
    forGeeks
    forGeek
    
  • replace( )It can replace one set of characters with another set inside a StringBuffer object by calling replace( ). The substring being replaced is specified by the indexes start Index and endIndex. Thus, the substring at start Index through endIndex–1 is replaced. The replacement string is passed in str.The resulting StringBuffer object is returned.Its signature is shown here:
    StringBuffer replace(int startIndex, int endIndex, String str)

    Code Example:

    filter_none

    edit

    play_arrow

    brightness_4

    import java.io.*;
    class GFG {
        public static void main(String[] args)
        {
            StringBuffer s = new StringBuffer("GeeksforGeeks");
            s.replace(5, 8, "are");
            System.out.println(s); // returns GeeksareGeeks
        }
    }
    Output:
    GeeksareGeeks
    
  • ensureCapacity( )It is used to increase the capacity of a StringBuffer object. The new capacity will be set to either the value we specify or twice the current capacity plus two (i.e. capacity+2), whichever is larger. Here, capacity specifies the size of the buffer.
    void ensureCapacity(int capacity)

    Besides that all the methods that are used in String class can also be used.

  • StringBuffer appendCodePoint(int codePoint): This method appends the string representation of the codePoint argument to this sequence.
    Syntax:

    public StringBuffer appendCodePoint(int codePoint)
    
  • char charAt(int index): This method returns the char value in this sequence at the specified index.
    Syntax:
    public char charAt(int index)
    
  • IntStream chars(): This method returns a stream of int zero-extending the char values from this sequence.
    Syntax:
    public IntStream chars()
    
  • int codePointAt(int index): This method returns the character (Unicode code point) at the specified index.
    Syntax:
    public int codePointAt(int index)
    
  • int codePointBefore(int index): This method returns the character (Unicode code point) before the specified index.
    Syntax:
    public int codePointBefore(int index)
    
  • int codePointCount(int beginIndex, int endIndex): This method returns the number of Unicode code points in the specified text range of this sequence.
    Syntax:
    public int codePointCount(int beginIndex,
                              int endIndex)
    
  • IntStream codePoints(): This method returns a stream of code point values from this sequence.
    Syntax:
    public IntStream codePoints()
    
  • void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin): In this method, the characters are copied from this sequence into the destination character array dst.
    Syntax:
    public void getChars(int srcBegin,
                         int srcEnd,
                         char[] dst,
                         int dstBegin)
    
  • int indexOf(String str): This method returns the index within this string of the first occurrence of the specified substring.
    Syntax:
    public int indexOf(String str)
    
    public int indexOf(String str,
                       int fromIndex)
    
  • int lastIndexOf(String str): This method returns the index within this string of the last occurrence of the specified substring.
    Syntax:
    public int lastIndexOf(String str)
    
    public int lastIndexOf(String str,
                           int fromIndex)
    
  • int offsetByCodePoints(int index, int codePointOffset): This method returns the index within this sequence that is offset from the given index by codePointOffset code points.
    Syntax:

    public int offsetByCodePoints(int index,
                                  int codePointOffset) 
    
  • void setCharAt(int index, char ch): In this method, the character at the specified index is set to ch.
    Syntax:
    public void setCharAt(int index,
                          char ch)
    
  • void setLength(int newLength): This method sets the length of the character sequence.
    Syntax:
    public void setLength(int newLength)
    
  • CharSequence subSequence(int start, int end): This method returns a new character sequence that is a subsequence of this sequence.
    Syntax:
    public CharSequence subSequence(int start,
                                    int end)
    
  • String substring(int start): This method returns a new String that contains a subsequence of characters currently contained in this character sequence.
    Syntax:
    public String substring(int start)
    
    public String substring(int start,
                            int end)
    
  • String toString(): This method returns a string representing the data in this sequence.
    Syntax:
    public String toString()
    
  • void trimToSize(): This method attempts to reduce storage used for the character sequence.
    Syntax:
    public void trimToSize()
    

 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

Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.




Comments

Popular posts from this blog

Privacy Policy

Privacy Policy Privacy Policy This privacy policy applies to the Rhino VPN app (hereby referred to as "Application") for mobile devices that was created by Codewithyaji (hereby referred to as "Service Provider") as a Free service. This service is intended for use "AS IS". What information does the Application obtain and how is it used? The Application does not obtain any information when you download and use it. Registration is not required to use the Application. Does the Application collect precise real time location information of the device? This Application does not collect precise information about the location of your mobile device. Do third parties see and/or have access to information obtained by the Application? Since the Application does not collect any information, no data is shared with third parties. What are my opt-out rights? You can stop all collection of information by the Application easily by uninstalling it. Yo...

Privacy Policy

Privacy Policy Privacy Policy Yajindra Gautam built the Gstatus app as an Ad Supported app. This SERVICE is provided by Yajindra Gautam at no cost and is intended for use as is. This page is used to inform visitors regarding my policies with the collection, use, and disclosure of Personal Information if anyone decided to use my Service. If you choose to use my Service, then you agree to the collection and use of information in relation to this policy. The Personal Information that I collect is used for providing and improving the Service. I will not use or share your information with anyone except as described in this Privacy Policy. The terms used ...

Privacy Policy for yajindra

Privacy Policy for yajindra At instagram-analytic, accessible from https://instagram-analytic.yajindragautam.com.np, one of our main priorities is the privacy of our visitors. This Privacy Policy document contains types of information that is collected and recorded by instagram-analytic and how we use it. If you have additional questions or require more information about our Privacy Policy, do not hesitate to contact us. This Privacy Policy applies only to our online activities and is valid for visitors to our website with regards to the information that they shared and/or collect in instagram-analytic. This policy is not applicable to any information collected offline or via channels other than this website. Consent By using our website, you hereby consent to our Privacy Policy and agree to its terms. Information we collect The personal information that you are asked to provide, and the reasons why you are asked to provide it, will be made clear to you at the point we as...