StringBuffer

java.lang.StringBuffer classes should be used when you have to make a lot of modifications to strings of characters. As we discussed in the previous section, String objects are immutable , so if you choose to do a lot of manipulations with String Objects, you will end up with a lot of abandoned String objects in the String pool.

Example:
	StringBuffer sb=new StringBuffer("Hello");
	sb.append("Java");
	System.out.println(sb);  //HelloJava
	
Note:In Jdk1.5 a new class is added StringBuilder, this class has same method as StringBuffer. The only difference between StringBuilder and StringBuffer is, StringBuffer is synchronized and StringBuilder is not synchrnoized,, and it is faster than StringBuffer.

StringBuffer methods

  1. append(String s):To append value on end , it can take boolean, float, int etc.
  2. Example:
    	StringBuffer s=new StringBuffer("Hello"); 
    	s.append(true);  //Output is Hellotrue
    
  3. delete(int start,int end):A substring is removed from the original object
  4. Example:
    	StringBuffer s=new StringBuffer("Hello");
    	s.delete(2,4);  //Heo
    
  5. insert(int offset,String s):To add value on desired location, and you can add any kind of value.
  6. Example:
    	StringBuffer s=new StringBuffer("1234567");
    	s.insert(4,"----");  //1234---567
    
  7. reverse():To reverse an original String.
  8. Example:
    	StringBuff	er s=new StringBuffer("Hello");
    	s.reverse();   //olleH
    
  9. deleteCharAt(int index):Delete a character from given index.
  10. StringBuffer s=new StringBuffer("Hello");
    s.deleteCharAt(2); //Helo
    	

String Buffer Class ( Since JDK 1.0)

  • JDK provides two classes to support mutable strings: StringBuffer and StringBuilder (in core package java.lang) .
  • A StringBuffer or StringBuilder object is just like any ordinary object, which are stored in the heap.
  • It can be modified without causing adverse side-effect to other objects.
  • In java we can't create StringBuffer Literals.
Example:
class Test{
   public static void main(String args[]){
     /* initialization of StringBuffer Object */
     StringBuffersb=new StringBuffer("StringBuffer");          
     System.out.println("After Initialization "+sb);
    /* Modify the value of StringBuffer Object */
    sb.append("Object");             
    System.out.println("After Updation "+sb);
   }
} 
OUTPUT
String Performance


Memory Layout of String Buffer Object:

String Buffer Object
Some important notes:
  • Create strings as literals instead of creating String objects using 'new' key word whenever possible
  • Use String.intern() method if you want to add number of equal objects whenever you create String objects using 'new' key word.
  • + operator gives best performance for String concatenation if Strings resolve at compile time
  • StringBuffer with proper initial size gives best performance for String concatenation if Strings resolve at run time.