Java String Buffer and Builder

Home   »   Java String Buffer and Builder

public class MyClass {
    public static void main(String args[]) {
        StringBuffer s = new StringBuffer("Rohan");
        s.append("arora");
        System.out.println(s);
        s.insert(2," arora ");
        System.out.println(s);
        s.replace(1,3,"pppp");
        System.out.println(s);
        s.delete(1,4);
        System.out.println(s);
        s.reverse();
        System.out.println(s);
        System.out.println(s.capacity());
        System.out.println(s.length());
        
        
        StringBuilder sb=new StringBuilder("Hello ");  
        sb.append("Java");//now original string is changed  
        System.out.println(sb);//prints Hello Java  
        sb.insert(1,"Java");//now original string is changed  
        System.out.println(sb);//prints HJavaello  
        sb.replace(1,3,"Java");  
        System.out.println(sb);//prints HJavalo 
        sb.delete(1,3);  
        System.out.println(sb);//prints Hlo  
        sb.reverse();  
        System.out.println(sb);//prints olleH   
        
        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  
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *