AdSense

AdSense3

Sunday 12 October 2014

Difference between 1. String and StringBuffer & 2. StringBuffer and StringBuilder

There are many differences between String and StringBuffer. A list of differences between String and StringBuffer are given below:

No.StringStringBuffer
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

  1. public class ConcatTest{  
  2.     public static String concatWithString()    {  
  3.         String t = "Java";  
  4.         for (int i=0; i<10000; i++){  
  5.             t = t + "Kundan";  
  6.         }  
  7.         return t;  
  8.     }  
  9.     public static String concatWithStringBuffer(){  
  10.         StringBuffer sb = new StringBuffer("Java");  
  11.         for (int i=0; i<10000; i++){  
  12.             sb.append("Kundan");  
  13.         }  
  14.         return sb.toString();  
  15.     }  
  16.     public static void main(String[] args){  
  17.         long startTime = System.currentTimeMillis();  
  18.         concatWithString();  
  19.         System.out.println("Time taken by Concating with String: "+(System.currentTimeMillis()-startTime)+"ms");  
  20.         startTime = System.currentTimeMillis();  
  21.         concatWithStringBuffer();  
  22.         System.out.println("Time taken by Concating with  StringBuffer: "+(System.currentTimeMillis()-startTime)+"ms");  
  23.     }  
  24. }  
Time taken by Concating with String: 578ms
Time taken by Concating with  StringBuffer: 0ms

String and StringBuffer HashCode Test

As you can see in the program given below, String returns new hashcode value when you concat string but StringBuffer returns same.
  1. public class InstanceTest{  
  2.     public static void main(String args[]){  
  3.         System.out.println("Hashcode test of String:");  
  4.         String str="java";  
  5.         System.out.println(str.hashCode());  
  6.         str=str+"Kundan";  
  7.         System.out.println(str.hashCode());  
  8.    
  9.         System.out.println("Hashcode test of StringBuffer:");  
  10.         StringBuffer sb=new StringBuffer("java");  
  11.         System.out.println(sb.hashCode());  
  12.         sb.append("Kundan");  
  13.         System.out.println(sb.hashCode());  
  14.     }  
  15. }  
Hashcode test of String:
3254818
229541438
Hashcode test of StringBuffer:
118352462
118352462

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.StringBufferStringBuilder
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

  1. public class BufferTest{  
  2.     public static void main(String[] args){  
  3.         StringBuffer buffer=new StringBuffer("hello");  
  4.         buffer.append("java");  
  5.         System.out.println(buffer);  
  6.     }  
  7. }  
hellojava

StringBuilder Example

  1. public class BuilderTest{  
  2.     public static void main(String[] args){  
  3.         StringBuilder builder=new StringBuilder("hello");  
  4.         builder.append("java");  
  5.         System.out.println(builder);  
  6.     }  
  7. }  
hellojava

Performance Test of StringBuffer and StringBuilder

Let's see the code to check the performance of StringBuffer and StringBuilder classes.
  1. public class ConcatTest{  
  2.     public static void main(String[] args){  
  3.         long startTime = System.currentTimeMillis();  
  4.         StringBuffer sb = new StringBuffer("Java");  
  5.         for (int i=0; i<10000; i++){  
  6.             sb.append("Kundan");  
  7.         }  
  8.         System.out.println("Time taken by StringBuffer: " + (System.currentTimeMillis() - startTime) + "ms");  
  9.         startTime = System.currentTimeMillis();  
  10.         StringBuilder sb2 = new StringBuilder("Java");  
  11.         for (int i=0; i<10000; i++){  
  12.             sb2.append("Kundan");  
  13.         }  
  14.         System.out.println("Time taken by StringBuilder: " + (System.currentTimeMillis() - startTime) + "ms");  
  15.     }  
  16. }  
Time taken by StringBuffer: 16ms
Time taken by StringBuilder: 0ms

Saturday 11 October 2014

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.

Important Constructors of StringBuilder class

  1. StringBuilder(): creates an empty string Builder with the initial capacity of 16.
  2. StringBuilder(String str): creates a string Builder with the specified string.
  3. StringBuilder(int length): creates an empty string Builder with the specified capacity as length.

Important methods of StringBuilder class

MethodDescription
public StringBuilder append(String s)is used to append the specified string with this string. The append() method is overloaded like append(char), append(boolean), append(int), append(float), append(double) etc.
public StringBuilder insert(int offset, String s)is used to insert the specified string with this string at the specified position. The insert() method is overloaded like insert(int, char), insert(int, boolean), insert(int, int), insert(int, float), insert(int, double) etc.
public StringBuilder replace(int startIndex, int endIndex, String str)is used to replace the string from specified startIndex and endIndex.
public StringBuilder delete(int startIndex, int endIndex)is used to delete the string from specified startIndex and endIndex.
public StringBuilder reverse()is used to reverse the string.
public int capacity()is used to return the current capacity.
public void ensureCapacity(int minimumCapacity)is used to ensure the capacity at least equal to the given minimum.
public char charAt(int index)is used to return the character at the specified position.
public int length()is used to return the length of the string i.e. total number of characters.
public String substring(int beginIndex)is used to return the substring from the specified beginIndex.
public String substring(int beginIndex, int endIndex)is used to return the substring from the specified beginIndex and endIndex.

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. }  

6) StringBuilder capacity() method

The capacity() method of StringBuilder class returns the current capacity of the Builder. The default capacity of the Builder is 16. If the number of character increases from its current capacity, it increases the capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be (16*2)+2=34.
  1. class A{  
  2. public static void main(String args[]){  
  3. StringBuilder sb=new StringBuilder();  
  4. System.out.println(sb.capacity());//default 16  
  5. sb.append("Hello");  
  6. System.out.println(sb.capacity());//now 16  
  7. sb.append("java is my favourite language");  
  8. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2  
  9. }  
  10. }  

7) StringBuilder ensureCapacity() method

The ensureCapacity() method of StringBuilder class ensures that the given capacity is the minimum to the current capacity. If it is greater than the current capacity, it increases the capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be (16*2)+2=34.
  1. class A{  
  2. public static void main(String args[]){  
  3. StringBuilder sb=new StringBuilder();  
  4. System.out.println(sb.capacity());//default 16  
  5. sb.append("Hello");  
  6. System.out.println(sb.capacity());//now 16  
  7. sb.append("java is my favourite language");  
  8. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2  
  9. sb.ensureCapacity(10);//now no change  
  10. System.out.println(sb.capacity());//now 34  
  11. sb.ensureCapacity(50);//now (34*2)+2  
  12. System.out.println(sb.capacity());//now 70  
  13. }  
  14. }