Monday 28 September 2015

StringBuffer in java with examples

Java stringBuffer class is used to created mutable string. The string java is same as string class except it is mutable that us can be changed.

String buffers are preferred when heavy modification of character strings is involved (appending, inserting, deleting, modifying etc).


## StringBuffer Functions : The following program explains the usage of the some of the basic StringBuffer methods like ;





  1. capacity() Returns the current capacity of the String buffer.
  2.  length() Returns the length (character count) of this string buffer.
  3. charAt(int index) The specified character of the sequence currently represented by the string buffer, as indicated by the index argument, is returned.
  4. setCharAt(int index, char ch) The character at the specified index of this string buffer is set to ch.
  5. toString() Converts to a string representing the data in this string buffer.
  6.  insert(int offset, char c) Inserts the string representation of the char argument into this string buffer.
  7. delete(int start, int end) Removes the characters in a substring of this StringBuffer
  8. replace(int start, int end, String str) Replaces the characters in a substring of this StringBuffer with characters in the specified String.
  9. reverse() The character sequence contained in this string buffer is replaced by the reverse of the sequence.
  10. append(String str) Appends the string to this string buffer.
  11. setLength(int newLength).




Note 


  1. That the StringBuffer class has got many overloaded ‘append’ methods which can be used based on the application need.
  2. That the StringBuffer class has got many overloaded ‘insert’ methods which can be used based on the application need.





# For Example:





/**
 *
 * @author pradeep
 */

public class DemoStringBuffer 
{

public static void main(String[] args)
 {
//     Examples of Creation of StringsBuffer
StringBuffer strBuff1 = new StringBuffer("Bob");
StringBuffer strBuff2 = new StringBuffer(400); //With capacity 100
StringBuffer strBuff3 = new StringBuffer(); //Default Capacity 16
System.out.println("stringBuffer1 : " + strBuff1);
System.out.println("stringBuffer2 capacity : " + strBuff2.capacity());
System.out.println("stringBuffer3 capacity : " + strBuff3.capacity());
}
}







Result:  Output of this program is:





run:


stringBuffer1 : Bob


stringBuffer2 capacity : 400


stringBuffer3 capacity : 16

BUILD SUCCESSFUL (total time: 1 second)





Note: If you have any problem then reply me.



No comments:

Post a Comment