StringBuffer & StringBuilder in Java


StringBuffer
The StringBuffer and StringBuilder classes are suitable for both assembling and modifying strings; i.e they provide methods for replacing and removing characters as well as adding them in various. Java StringBuilder class is used to create mutable (modifiable) string.

Key Points:

  • Used to created mutable (modifiable) string.
  • Mutable: Which can be changed?
  • Is thread-safe i.e. multiple threads cannot access it simultaneously.

Methods:

  • public synchronized StringBuffer append ( String s )
  • public synchronized StringBuffer insert ( int offset, String s )
  • public synchronized StringBuffer replace ( int startIndex, int endIndex, String str )
  • public synchronized StringBuffer delete ( int startIndex, int endIndex )
  • public synchronized StringBuffer reverse ()

StringBuilder
Java StringBuilder class is used to create mutable (modifiable) string. The Java StringBuilder class is same as StringBuffer class except that it is non-synchronized. The StringBuffer and StringBuilder classes are suitable for both assembling and modifying strings; i.e they provide methods for replacing and removing characters as well as adding them in various.

Source Code

public class stringBuffer_stringBuilder {
    public static void main(String args[])
    {
        //StringBuffer & StringBuilder in Java
 
        StringBuilder buffer =new StringBuilder("Tutor");
        System.out.println(buffer);
        buffer.append(" Joes");
        System.out.println(buffer);
        buffer.insert(10," Computer");
        System.out.println(buffer);
        buffer.replace(9,11,"@@@");
        System.out.println(buffer);
        buffer.delete(9,11);
        System.out.println(buffer);
        buffer.reverse();
        System.out.println(buffer);
        System.out.println(buffer.charAt(2));
        System.out.println(buffer.length());
        System.out.println(buffer.substring(0));
        System.out.println(buffer.substring(0,5));
        buffer.setCharAt(0,'@');
        System.out.println(buffer);
 
        StringBuffer sb=new StringBuffer();
        System.out.println(sb.capacity());//default 16
        sb.append("Hello");
        System.out.println(sb.capacity());//now 16
        sb.append("java is my favourite language");
        System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
 
    }
}
 

Output

Tutor
Tutor Joes
Tutor Joes Computer
Tutor Joe@@@Computer
Tutor Joe@Computer
retupmoC@eoJ rotuT
t
18
retupmoC@eoJ rotuT
retup
@etupmoC@eoJ rotuT
16
16
34
To download raw file Click Here

Basic Programs