Likes

Java StringBuffer class


Java StringBuffer class
Java StringBuffer class is used to created mutable (modifiable) string. The StringBuffer class in java is same as String class except it is mutable i.e. it can be changed.
Note: Java StringBuffer class is thread-safe i.e. multiple threads cannot access it simultaneously. So it is safe and will result in an order.

What is mutable string
A string that can be modified or changed is known as mutable string. StringBuffer and StringBuilder classes are used for creating mutable string.
1) StringBuffer append() method
The append() method concatenates the given argument with this string.
class A{  
public static void main(String args[]){  
StringBuffer sb=new StringBuffer("Hello ");  
sb.append("Java");//now original string is changed  
System.out.println(sb);//prints Hello Java  
}  
}  
2) StringBuffer insert() method
The insert() method inserts the given string with this string at the given position.
class A{  
public static void main(String args[]){  
StringBuffer sb=new StringBuffer("Hello ");  
sb.insert(1,"Java");//now original string is changed  
System.out.println(sb);//prints HJavaello  
}  
}  
3) StringBuffer replace() method
The replace() method replaces the given string from the specified beginIndex and endIndex.
class A{  
public static void main(String args[]){  
StringBuffer sb=new StringBuffer("Hello");  
sb.replace(1,3,"Java");  
System.out.println(sb);//prints HJavalo  
}  
}  
4) StringBuffer delete() method
The delete() method of StringBuffer class deletes the string from the specified beginIndex to endIndex.
class A{  
public static void main(String args[]){  
StringBuffer sb=new StringBuffer("Hello");  
sb.delete(1,3);  
System.out.println(sb);//prints Hlo  
}  
}  
5) StringBuffer reverse() method
The reverse() method of StringBuilder class reverses the current string.
class A{  
public static void main(String args[]){  
StringBuffer sb=new StringBuffer("Hello");  
sb.reverse();  
System.out.println(sb);//prints olleH  
}  
}  
Java StringBuilder class
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. It is available since JDK 1.5.
Java StringBuilder Examples
Let's see the examples of different methods of StringBuilder class.
1) StringBuilder append() method
The StringBuilder append() method concatenates the given argument with this string.
1.    class A{  
2.    public static void main(String args[]){  
3.    StringBuilder sb=new StringBuilder("Hello ");  
4.    sb.append("Java");//now original string is changed  
5.    System.out.println(sb);//prints Hello Java  
6.    }  
7.    }  
2) StringBuilder insert() method
The StringBuilder insert() method inserts the given string with this string at the given position.
1.    class A{  
2.    public static void main(String args[]){  
3.    StringBuilder sb=new StringBuilder("Hello ");  
4.    sb.insert(1,"Java");//now original string is changed  
5.    System.out.println(sb);//prints HJavaello  
6.    }  
7.    }  
3) StringBuilder replace() method
The StringBuilder replace() method replaces the given string from the specified beginIndex and endIndex.
1.    class A{  
2.    public static void main(String args[]){  
3.    StringBuilder sb=new StringBuilder("Hello");  
4.    sb.replace(1,3,"Java");  
5.    System.out.println(sb);//prints HJavalo  
6.    }  
7.    }  
4) StringBuilder delete() method
The delete() method of StringBuilder class deletes the string from the specified beginIndex to endIndex.
1.    class A{  
2.    public static void main(String args[]){  
3.    StringBuilder sb=new StringBuilder("Hello");  
4.    sb.delete(1,3);  
5.    System.out.println(sb);//prints Hlo  
6.    }  
7.    }  
5) StringBuilder reverse() method
The reverse() method of StringBuilder class reverses the current string.
1.    class A{  
2.    public static void main(String args[]){  
3.    StringBuilder sb=new StringBuilder("Hello");  
4.    sb.reverse();  
5.    System.out.println(sb);//prints olleH  
6.    }  
7.    }  

Difference between String and StringBuffer
There are many differences between String and StringBuffer. A list of differences between String and StringBuffer are given below:
No.
String
StringBuffer
1)
String class is immutable.
StringBuffer class is mutable.
2)
String is slow and consumes more memory when you concat too many strings because every time it creates new instance.
StringBuffer is fast and consumes less memory when you cancat strings.
3)
String class overrides the equals() method of Object class. So you can compare the contents of two strings by equals() method.
StringBuffer class doesn't override the equals() method of Object class.
Performance Test of String and StringBuffer
public class ConcatTest{  
    public static String concatWithString()    {  
        String t = "Java";  
        for (int i=0; i<10000; i++){  
            t = t + "Tpoint";  
        }  
        return t;  
    }  
    public static String concatWithStringBuffer(){  
        StringBuffer sb = new StringBuffer("Java");  
        for (int i=0; i<10000; i++){  
            sb.append("Tpoint");  
        }  
        return sb.toString();  
    }  
    public static void main(String[] args){  
        long startTime = System.currentTimeMillis();  
        concatWithString();  
        System.out.println("Time taken by Concating with String: "+(System.currentTimeMillis()-startTime)+"ms");  
        startTime = System.currentTimeMillis();  
        concatWithStringBuffer();  
        System.out.println("Time taken by Concating with  StringBuffer: "+(System.currentTimeMillis()-startTime)+"ms");  
    }  
}  
Time taken by Concating with String: 578ms
Time taken by Concating with  StringBuffer: 0ms
Difference between StringBuffer and StringBuilder
There are many differences between StringBuffer and StringBuilder. A list of differences between StringBuffer and StringBuilder are given below:
No.
StringBuffer
StringBuilder
1)
StringBuffer is synchronized i.e. thread safe. It means two threads can't call the methods of StringBuffer simultaneously.
StringBuilder is non-synchronized i.e. not thread safe. It means two threads can call the methods of StringBuilder simultaneously.
2)
StringBuffer is less efficient than StringBuilder.
StringBuilder is more efficient than StringBuffer.

StringBuffer Example
public class BufferTest{  
    public static void main(String[] args){  
        StringBuffer buffer=new StringBuffer("hello");  
        buffer.append("java");  
        System.out.println(buffer);  
    }  
}  
hellojava
StringBuilder Example
public class BuilderTest{  
    public static void main(String[] args){  
        StringBuilder builder=new StringBuilder("hello");  
        builder.append("java");  
        System.out.println(builder);  
    }  
}  
hellojava
Performance Test of StringBuffer and StringBuilder
Let's see the code to check the performance of StringBuffer and StringBuilder classes.
public class ConcatTest{  
    public static void main(String[] args){  
        long startTime = System.currentTimeMillis();  
        StringBuffer sb = new StringBuffer("Java");  
        for (int i=0; i<10000; i++){  
            sb.append("Tpoint");  
        }  
        System.out.println("Time taken by StringBuffer: " + (System.currentTimeMillis() - startTime) + "ms");  
        startTime = System.currentTimeMillis();  
        StringBuilder sb2 = new StringBuilder("Java");  
        for (int i=0; i<10000; i++){  
            sb2.append("Tpoint");  
        }  
        System.out.println("Time taken by StringBuilder: " + (System.currentTimeMillis() - startTime) + "ms");  
    }  
}  
Time taken by StringBuffer: 16ms
Time taken by StringBuilder: 0ms

Java toString() method
If you want to represent any object as a string, toString() method comes into existence.
The toString() method returns the string representation of the object.
If you print any object, java compiler internally invokes the toString() method on the object. So overriding the toString() method, returns the desired output, it can be the state of an object etc. depends on your implementation.
Advantage of Java toString() method
By overriding the toString() method of the Object class, we can return values of the object, so we don't need to write much code.



Understanding problem without toString() method
Let's see the simple code that prints reference.
1.    class Student{  
2.     int rollno;  
3.     String name;  
4.     String city;  
5.      
6.     Student(int rollno, String name, String city){  
7.     this.rollno=rollno;  
8.     this.name=name;  
9.     this.city=city;  
10.  }  
11.   
12.  public static void main(String args[]){  
13.    Student s1=new Student(101,"Raj","lucknow");  
14.    Student s2=new Student(102,"Vijay","ghaziabad");  
15.      
16.    System.out.println(s1);//compiler writes here s1.toString()  
17.    System.out.println(s2);//compiler writes here s2.toString()  
18.  }  
19. }  
Output:Student@1fee6fc
       Student@1eed786
As you can see in the above example, printing s1 and s2 prints the hashcode values of the objects but I want to print the values of these objects. Since java compiler internally calls toString() method, overriding this method will return the specified values. Let's understand it with the example given below:




Example of Java toString() method
Now let's see the real example of toString() method.
1.    class Student{  
2.     int rollno;  
3.     String name;  
4.     String city;  
5.      
6.     Student(int rollno, String name, String city){  
7.     this.rollno=rollno;  
8.     this.name=name;  
9.     this.city=city;  
10.  }  
11.    
12.  public String toString(){//overriding the toString() method  
13.   return rollno+" "+name+" "+city;  
14.  }  
15.  public static void main(String args[]){  
16.    Student s1=new Student(101,"Raj","lucknow");  
17.    Student s2=new Student(102,"Vijay","ghaziabad");  
18.      
19.    System.out.println(s1);//compiler writes here s1.toString()  
20.    System.out.println(s2);//compiler writes here s2.toString()  
21.  }  
22. }  
Output:101 Raj lucknow
       102 Vijay ghaziabad

StringTokenizer in Java
The java.util.StringTokenizer class allows you to break a string into tokens. It is simple way to break string.
It doesn't provide the facility to differentiate numbers, quoted strings, identifiers etc. like StreamTokenizer class. We will discuss about the StreamTokenizer class in I/O chapter.
Simple example of StringTokenizer class
Let's see the simple example of StringTokenizer class that tokenizes a string "my name is khan" on the basis of whitespace.
import java.util.StringTokenizer;  
public class Simple{  
 public static void main(String args[]){  
   StringTokenizer st = new StringTokenizer("my name is karan"," ");  
     while (st.hasMoreTokens()) {  
         System.out.println(st.nextToken());  
     }  
   }  
}  
Output:my
       name
       is
       karan



Example of nextToken(String delim) method of StringTokenizer class
import java.util.*;  
  
public class Test {  
   public static void main(String[] args) {  
       StringTokenizer st = new StringTokenizer("my,name,is,karan");  
        
      // printing next token  
      System.out.println("Next token is : " + st.nextToken(" "));  
   }      
}  
Output:Next token is : my
StringTokenizer class is deprecated now. It is recommended to use split() method of String class or regex (Regular Expression).



No comments: