STRINGBUILDER & STRINGBUFFER, STRINGTOKENIZER

StringBuffer


  • String buffer is a class it has some features as a string class except immutable.

  • By using string buffer also we can handle bundle (or) set (or) sequence of characters.

  • For string buffer class we can create object, only in one way by using new operator.

  • string buffer supports 100% synchronisation that means every method (or) member inside string buffer a supports thread safety or synchronisation.

  • It means, at a time only one thread can access string buffer object.

  • If it allows multiple threads at a time we will get data corruption.

  • javapadho
    Heap memory by manage by String class
  • In the above we will get data coruption why because at a time two threads are processing.

  • String buffer will creates mutable objects.if we try to modify the orignal object changes will effect in the same location . it wont creates new object like string class.

  • Some important methods in string Buffer:

      It comes under java.lang.StringBuffer package.

    • Syntax:

    • StringBuffer sb=new StringBuffer(string value);

      append():

      • The append() method is same as concat method in the string class. It will append (or) concat a new value to the existing object .

      • By using append() method we can append any type of values( i.e int , float, double, long……. ) .

      • Example 1:

         
        		         
                          public class Append1
                          {
                              public static void main(String[] args) 
                              {
                                  StringBuffer sb=new StringBuffer("Praveen");
                                  System.out.println("string is :" +sb);
                                  sb.append("kumar");
                                  System.out.println("After append:" +sb);
                                  String str=new String("SDJ");
                                  System.out.println("Given string:" +str);
                                  str.concat("JAVA");
                                  System.out.println("After Concat:" +str);
                              }
                          }                 

           Output:

        Given String is:Praveen After append:Praveenkumar Given string:SDJ After Concat:SDJ
      • The StringBuffer class produce mutable objects ,since it will apply modifications in original object only. it does not creates the new object like String class.

      • String class produce immutable objects, it does not apply modifications on original object directly. it will creates new object with updated value.and return that new object to the user.

      • Inside StringBuffer the toString( ) method is already overrided based on content/state of the object.

      • Example 2:

         
        				 
                      public class StrBuffer
                      {
                         public static void main(String[] args) 
                         {
                            StringBuffer sb1 = new StringBuffer(" sdj ");
                            StringBuffer sb2 = new StringBuffer(" sdj ");
                            StringBuffer sb3 = null;
                            System.out.println("string sb1 : "+sb1);
                            System.out.println("string sb2 : "+sb2);
                            System.out.println("string sb3 : "+sb3);
                            System.out.println(sb1.equals(sb2));
                            System.out.println(sb3.equals(sb1));
                            System.out.println(sb1.hashCode()==sb2.hashCode());
                         }
                      }                 

           Output:

        string sb1:SDJ string sb2:SDJ string sb3:SDJ false true false
      • In the above output, the equals( ) method and hashcode( ) method returns false why because inside string buffer the equals( ) method and hashcode( ) method are not overrided only toString( ) method was overrided.

      • Inside string buffer the equals( ) method and hashcode( ) method works based on the memory location but not on the content of the object.


      delete():

      • The delete( ) method will delete the characters from the original object with the specified index range.

      • Inside string buffer the delete( ) method is synchronized.

      • Syntax:

      • Public synchronized StringBuffer delete(int startindex , int endIndex);
        Note

        It will delete the characters within the specified range (i.e starting index to ending index)

      • Syntax:

      • Public synchronized StringBuffer deleteCharAt(int index);
        Note

        It will delete the character with a specified index value.

        Example 3:

         
        		 		 
                      public class StringBufferDelete
                      {
                         public static void main(String[] args)
                         {
                            StringBuffer sb=new StringBuffer("we Are Two But..Our Goal Is One");
                            System.out.println("Entered string:" +sb);
                            sb.delete(10,14);
                            System.out.println(sb);
                            StringBuffer sb1=new StringBuffer("sdj");
                            System.out.println("Entered string is:"+sb1);
                            sb1.deleteCharAt(3);
                            System.out.println(sb1);
                         }
                      }                 

           Output:

        Entered string:we Are Two But..Our Goal Is One we Are Two..Our Goal Is One Entered string is:sdj SDJ

      insert():

      • It is one of the important method in string buffer.

      • insert( ) method will act same as append( ) but by using insert( ) method we can insert the value in specified index. But append( ) method will always add at the end of the original object.

      • By using insert method we can insert any type of values (i.e char,string,int,byte,short,long ,double,float,Boolean values).

      • Insert( ) method is also a synchronized one.

      • Syntax:

      • Public synchronized StringBuffer insert(int index , char c);
        Public synchronized StringBuffer insert(int index , String s);
        Public synchronized StringBuffer insert(int index , int i);
        Public synchronized StringBuffer insert(int index , byte b);
        Public synchronized StringBuffer insert(int index , short s);
        Public synchronized StringBuffer insert(int index , long l);
        Public synchronized StringBuffer insert(int index , double d);
        Public synchronized StringBuffer insert(int index , float f);
        Public synchronized StringBuffer insert(int index , boolean bi);

        Example 4:

         
        		 		 
                      package com.sdj.pack1;
                      public class InsertExample
                      {
                         public static void main(String[] args)
                         {
                             StringBuffer sb=new StringBuffer("SDJ");
                            System.out.println(sb);
                            sb.insert(3,"INFO");
                            System.out.println(sb);
                            sb.insert(7, "@12343SOFT");
                            System.out.println(sb);
                            StringBuffer sb1=new StringBuffer("Praveen");
                            System.out.println(sb1);
                            sb1.insert(7, "kumar");
                            System.out.println(sb1);
                            sb1.append("1985");
                            System.out.println(sb1);
                         }
                      }                 

           Output:

        SDJ SDJINFO SDJINFO@12343SOFT Praveen Praveenkumar Praveenkumar1985

      reverse():

      • The reverse( ) method will change the object value in reverse order.

      • Syntax:

      • Public synchronized StringBuffer reverse( );
      • It has only one method with no arguments.

      • Example 4:

         
        				 
                      public class ReverseExample
                      {
                         public static void main(String[] args)
                         {
                             StringBuffer sb = new StringBuffer("Hello World");
                            System.out.println("Entered String : "+sb);
                            sb.reverse();
                            System.out.println("Reverse of String : "+sb);
                            StringBuffer sb1 = new StringBuffer(" sdj ");
                            System.out.println("Entered String : "+sb1);
                            sb1.reverse();
                            System.out.println("Reverse of String :"+sb1);   
                         }
                      }                 

           Output:

        Entered string: Hello World Reverse of string: dlroW olleH Entered string: SDJ Reverse of string: JDS
      • In String Buffer we will get less performance due to synchronization or thread safety.

      • In order to overcome this drawback of String Buffer ,sun people came up with one new class it’s named as String Builder. It is one of the feature in jdk1.5.


StringBuffer

  • It is same as the StringBuffer except synchronization or thread safety.

  • String Builder allows multiple threads at a time. So through String Builder we can achieve more performance and less accuracy.

  • String Builder contain the methods which are same as in StringBuffer with out synchronization.

  • Note
    • String [ ] is not equal to string class.

    • String [ ] is a collection of string objects but String class contain only one string object.

String Tokenizer

  • String Tokenizer is a class for manipulating string objects in advanced . It is a part of jdk 1.5 version.

  • It is available under java.util package.

  • String Tokenizer is mainly used for splitting the given string with specified delimetter.

  • It is mainly used for splitting purpose only.

  • It is same as split method in string class, but it gives output based on the index value.

  • But as a java developer we should not work based on the index value and memory location.

  • To overcome the drawback of split method sun people came up with one method called string Tokenizer.

  • Example 5:

     
    				 
                  package com.sdj.pack1;
                  import java.util.StringTokenizer;
                  public class StringTokenizerEX 
                  {
                     public staticvoid main(String[] args)
                     {
                        String s="abc;pqr;xyz;123;456" ;
                        System.out.println("Entered String:"+s);
                        StringTokenizer st= new StringTokenizer(s,";");
                        System.out.println("After Tokenizing");
                        while(st.hasMoreElements())
                        {
                            System.out.println(st.nextElement());
                        }
                     }
                  }                 

       Output:

    Entered String:abc;pqr;xyz;123;456 After Tokenizing abc pqr xyz 123 456
  • In string Tokenizer hasMoreElements( ) returns Boolean value (i.e..true/false). It will return true if it finds the delimetter( ;) between string

  • In this nextElement( ) will return a value of delimetter before content.it is same as group( ) method inside matched class.

  • In the above StringTokenizer class can also use hasMoreTokens( ) and nextToken()methods to reading elements from StringTokenizer. like bellow

      while(st. hasMoreTokens( ))
      {
        System.out.println(st.nextToken ());
      }
  • Finding the number of words in string using String Tokenizer:

    • By using countTokens( ) method it will returns the number of words based on the delimiter in the integer format.

    • Syntax:

    • StringTokenizer st=new StringTokenizer(string value);

      Example 6:

       
      				 
                    package com.sdj.pack1;
                   
                    import java.util.StringTokenizer;
                        
                    public class TokenizerEx
                    {
                       public static void main(String[] args) 
                       {
                          StringTokenizer st = new StringTokenizer("abc;pqr;xyz;123;567");
                          System.out.println(st.countTokens());
                       }
                    }                 

         Output:

      1