"StringBuffer" And "StringBuilder" Classes In JAVA

Discussion in 'Java' started by techgeek.in, May 26, 2010.

  1. techgeek.in

    techgeek.in New Member

    Joined:
    Dec 20, 2009
    Messages:
    572
    Likes Received:
    19
    Trophy Points:
    0
    Occupation:
    EOC (exploitation of computers)..i m a Terminator.
    Location:
    Not an alien!! for sure
    Home Page:
    http://www.techgeek.in

    Introduction



    The instances of the String class represent a string that cannot be modified. If we do want to create modifiable strings because we are going to do lots of string manipulation, we should use the java.lang.StringBuffer and java.lang.StringBuilder classes.If we choose to do a lot of manipulations with String objects, we will end up with a lot of abandoned String objects in the String pool. Objects of type StringBuffer and StringBuilder can be modified over and over again without leaving behind a great effluence of discarded String objects.
    A common use for StringBuffers and StringBuilders is file I/O when large, ever-changing streams of input are being handled by the program. In these cases, large blocks of characters are handled as units, and StringBuffer objects are the ideal way to handle a block of data, pass it on, and then reuse the same memory to handle the next block of data.

    StringBuffer Class

    StringBuffer is a peer class that provides much of the functionality of strings. It represents growable and writeable character sequences. They may have characters and substrings inserted in the middle or appended to the end.

    StringBuilder Class

    The StringBuilder class was added in Java 5. It has exactly the same API as the StringBuffer class, except StringBuilder is not thread safe. In other words, its methods are not synchronized. Sun recommends that you use StringBuilder instead of StringBuffer whenever possible because StringBuilder will run faster. So apart from synchronization, anything we say about StringBuilder's methods holds true for StringBuffer's methods, and vice versa.

    StringBuffer Constructors



    This class provides three constructors:

    StringBuffer( )
    StringBuffer(int size)
    StringBuffer(String str)

    The constructor with no parameter is the default constructor which reserves room for 16 characters without reallocation. The second version accepts an integer argument that explicitly sets the size of the buffer. The third version accepts a String argument that sets the initial contents of the StringBuffer object and reserves room for 16 more characters without reallocation. StringBuffer allocates room for 16 additional characters when no specific buffer length is requested, because reallocation is a costly process in terms of time. Also, frequent reallocations can fragment memory. By allocating room for a few extra characters, StringBuffer reduces the number of reallocations that take place.

    We can create a string by passing the string value as an argument of the StringBuffer class constructor, as shown here:

    Code:
    StringBuffer sb = new StringBuffer("Hello Dear!");
    
    We can also pass in a String reference as a variable:

    Code:
    String str = "Hello Dear!";
    StringBuffer sb = new StringBuffer(str);
    

    Methods of StringBuffer and StringBuilder Classes



    All the methods of both the classes are similar except that StringBuilder methods are not thread safe.

    • int length( ) method

      The current length of a StringBuffer or StringBuilder string can be obtained from the length() method.
      For example,

      Code:
      StringBuffer sb = new StringBuffer("Hello");
      System.out.println("buffer = " + sb);        //output is "buffer = Hello"
      System.out.println("length = " + sb.length());  //output is "length = 5"
      
      Since sb is initialized with the string “Hello” when it is created, its length is 5.

    • int capacity( ) method

      The total allocated capacity of a StringBuffer or StringBuilder string can be found through the capacity() method.
      For example,

      Code:
      StringBuffer sb = new StringBuffer("Hello");
      System.out.println("buffer = " + sb);             //output is "buffer = Hello"
      System.out.println("capacity = " + sb.capacity());  //output is "capacity = 21"
      
      The capacity of sb is 21 because room for 16 additional characters is automatically added.

    • void ensureCapacity(int capacity)

      If we want to preallocate room for a certain number of characters after a StringBuffer
      has been constructed, we can use ensureCapacity( ) to set the size of the buffer. This is
      useful if we know in advance that we will be appending a large number of small strings to a StringBuffer.

    • void setLength(int nlength)

      This method sets the new length of the current string buffer to nlength. If nlength is smaller than the length of the current string buffer, it is truncated. If nlength is greater than the current length, the null characters are added to the end of the string buffer.

    • public synchronized StringBuffer append(String s)

      This method will update the value of the string that invoked the method by appending the contents of the string s to the invoking string object whether or not the return is assigned to a variable. This method will take many different arguments, including boolean, char, double, float, int, long, and others when String.valueOf( ) is called to obtain its string representation of the argument.
      For example,

      Code:
      class appendDemo
       {
        public static void main(String args[]) 
         {
           StringBuffer sb = new StringBuffer("set ");
           sb.append("point");
           System.out.println(sb);       // output is "set point"
           StringBuffer sb2 = new StringBuffer("pi = ");
           sb2.append(3.14159f);
           System.out.println(sb2);
            // output is  "pi = 3.14159"
         }
       }
      
    • public StringBuffer delete(int start, int end)

      This method returns a StringBuffer object and updates the value of the StringBuffer object that invoked the method call. In both cases, a substring is removed from the original object. The starting index of the substring to be removed is defined by the first argument (which is zero-based), and the ending index of the substring to be removed is defined by the second argument (but it is one-based).

      For example,

      Code:
      StringBuffer sb = new StringBuffer("0123456789");
      System.out.println(sb.delete(4,6));      // output is "01236789"
      
    • public StringBuffer insert(int offset, String s)

      This method returns a StringBuffer object and updates the value of the StringBuffer object that invoked the method call. In both cases, the String passed in to the second argument is inserted into the original starting at the offset location represented by the first argument (the offset is zero-based). Again, other types of data can be passed in through the second argument (boolean, char, double, float, int, long, and so on).
      For example,

      Code:
      StringBuffer sb = new StringBuffer("01234567");
      sb.insert(4, "---");
      System.out.println( sb );          //   output is  "0123---4567"
      
    • public synchronized StringBuffer reverse()

      This method returns a StringBuffer object and updates the value of the StringBuffer object that invoked the method call. In both cases, the characters in the StringBuffer are reversed, the first character becoming the last, the second becoming the second to the last, and so on.

      For example,

      Code:
      StringBuffer s = new StringBuffer("A man a plan a canal Panama");
      sb.reverse();
      System.out.println(sb); // output: "amanaP lanac a nalp a nam A"
      
    • StringBuffer replace(int startIndex, int endIndex, String str)

      This method replaces one set of characters with another set inside a StringBuffer object.The substring being replaced is specified by the indexes startIndex and endIndex. Thus,the substring at startIndex through endIndex–1 is replaced. The replacement string is passed in str. The resulting StringBuffer object is returned.

      For example,

      Code:
      StringBuffer sb = new StringBuffer("This is a test.");
      sb.replace(5, 7, "was");
      System.out.println("After replace: " + sb);  //output is "After replace: This was a test"
      
    • void setCharAt(int offset, char ch)

      This method replaces the character at position offset in the current buffer string with the new character specified by ch and returns the invoking replaced string.
      For example,

      Code:
      StringBuffer sb = new StringBuffer("Hello");
      System.out.println("buffer before = " + sb);    //output is "buffer before = Hello"
      sb.setCharAt(1, 'i');
      sb.setLength(2);
      System.out.println("buffer after = " + sb);    //output is "buffer after = Hi"
      
    • public String toString()

      This method returns the value of the StringBuffer object that invoked the method call as a String.
      For example,

      Code:
      StringBuffer sb = new StringBuffer("test string");
      System.out.println( sb.toString() );  // output is "test string"
      

    Comparison



    A string created with the String class cannot be modified, whereas a string created with the StringBuffer class can be modified. The equals(…) method in the String class returns true if both strings are identical, while the equals(…) method in the StringBuffer class returns true only if both string references refer to the same string.Because the StringBuffer class, unlike the String class, is designed to be thread safe (i.e. multiple threads can use a StringBuffer string in a synchronized way), we pay some price in terms of performance. If we know that our application is only a single-threaded application, we can use the StringBuilder class (which has the same functionality as the StringBuffer class), which will somewhat improve the performance but will not guarantee synchronization.
     
  2. seozest

    seozest New Member

    Joined:
    May 31, 2010
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    Thanks a lot.
    quality info on such complicated topic.
    will be very useful practically.

    -----------------------------
    Outsourced Product Development
    e-Zest Solutions
     
  3. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice