Google+

144. StringBuffer class







StringBuffer is a class similar to String class with a difference.  String represents fixed length and cannot be modified character sequence. But StringBuffer is not of fixed length and also the character sequence can be modified.

Example: (You can modify the character sequence using StringBuffer but not using String class)

If you want to reverse the characters in the specified string, then you have to declare the specified string using StringBuffer class instead of String class.

----------------------------------------------------------------------------------------------------------------------------------------------------------

StringBuffer sb = new StringBuffer("abcdef");

sb.reverse( );  -> Will give the result as fedcba  (i.e. the character sequence can be modified)

----------------------------------------------------------------------------------------------------------------------------------------------------------

String s =  "abcdef";

s.reverse( );  -> This will throw an error as the character sequence cannot be modified for a String class object.

----------------------------------------------------------------------------------------------------------------------------------------------------------

The following methods can be used with the StringBuffer's class objects:

1. length( )   -------> Gives the current length of the StringBuffer object
2. capacity( )  -------> Gives the total allocated capacity of the StringBuffer object
3. setLength( ) -------> Sets the length of the StringBuffer object 
4. charAt( ) -------> To extract the character from the string using the specified index
5setCharAt( ) -------> Replaces the character with another at the specified index.
6getChars( ) -------> Extracts the substring from the specified string and copies into a char array.
7append( ) -------> Appends different types of data to the StringBuffer object
8insert( ) -------> Inserts one string into the another
9reverse( ) -------> Reverses the characters in the StringBuffer object (last character will be displayed first and first character will be displayed last)
10delete( ) -------> Deletes a set of characters in the specified string
11deleteCharAt( ) -------Deletes the character at the specified index 
12replace( ) -------Replaces the set of characters with the another set of characters
13. substring( ) -------Extracts a portion of the StringBuffer's object
14. indexOf( ) -------Searches for the first occurrence of a string in the StringBuffer's object
15lastIndexOf( ) -------Searches for the last occurrence of a string in the StringBuffer's object




Please comment below to feedback or ask questions.

Using 'length( )' method with the StringBuffer will be explained in the next post.




No comments: