Thursday, June 12, 2014

StringBuffer / StringBuilder - Example




Examples of StringBuffer



import java.util.*;
public class StrBuf
    {
        public static void main(String[] args)
            {
                Scanner Sc=new Scanner(System.in);
                String S;
                System.out.print("\tEnter a String : ");
                S=Sc.nextLine();
                StringBuffer Sb = new StringBuffer(S);
                System.out.println("\tInput String '"+S+"'");
                StrBuf Buf=new StrBuf();
                Buf.AID(Sb);
            }
        void AID(StringBuffer Sb)
            {
                Sb.insert(11," A");
                System.out.println("\tAfter Insert 'A ' the new String  '"+Sb+"'");
                Sb.append(" AND THERE'S A WAY");
                System.out.println("\tAfter Append '"+Sb+"'");
                Sb.delete(18,22);
                System.out.println("\tAfter Deleting 'and ' the new String  '"+Sb+"'");
               
            }
    }


Output:


          Enter a String : IF THERE IS WILL
          Input String 'IF THERE IS WILL'
          After Insert 'A ' the new String  'IF THERE IS A WILL'
          After Append 'IF THERE IS A WILL AND THERE'S A WAY'
          After Deleting 'and ' the new String  'IF THERE IS A WILL THERE'S A WAY'



Examples of StringBuilder




import java.util.*;
    public class StrBld
        {
        public static void main(String[] args)
            {
                Scanner Sc=new Scanner(System.in);
                String S;
                System.out.print("\tEnter a String : ");
                S=Sc.nextLine();
                StringBuilder Sb = new StringBuilder(S);
                System.out.println("\tInput String '"+S+"'");
                StrBld Bld=new StrBld();
                Bld.AID(Sb);
            }
        void AID(StringBuilder Sb)
            {
                Sb.insert(11," A");
                System.out.println("\tAfter Insert 'A ' the new String  '"+Sb+"'");
                Sb.append(" AND THERE'S A WAY");
                System.out.println("\tAfter Append '"+Sb+"'");
                Sb.delete(18,22);
                System.out.println("\tAfter Deleting 'and ' the new String  '"+Sb+"'");
               
            }
    }



Output:


          Enter a String : IF THERE IS WILL
          Input String 'IF THERE IS WILL'
          After Insert 'A ' the new String  'IF THERE IS A WILL'
          After Append 'IF THERE IS A WILL AND THERE'S A WAY'
          After Deleting 'and ' the new String  'IF THERE IS A WILL THERE'S A WAY'




No comments: