Friday 28 June 2013

: StringBuffer and StringBuilder:

 StringBuffer and StringBuilder

The StringBuilder class was introduced with JDK 5.0. Essentially, a StringBuffer is a thread-safe version of StringBuilder. If you are only adding/removing characters from a single-thread, the StringBuilder implementation will be faster. If you are using multiple threads to add and remove characters, use StringBuffer

Difference between String and StringBuffer/StringBuilder in Java

Well, the most important difference between String and StringBuffer/StringBuilder in java is that String object is immutable whereas StringBuffer/StringBuilder objects are mutable.
By immutable, we mean that the value stored in the String object cannot be changed. Then the next question that comes to our mind is “If String is immutable then how am I able to change the contents of the object whenever I wish to?” . Well, to be precise it’s not the same String object that reflects the changes you do. Internally a new String object is created to do the changes.
So suppose you declare a String object:
String myString = “Hello”;
Next, you want to append “Guest” to the same String. What do you do?
myString = myString + ” Guest”;
When you print the contents of myString the output will be “Hello Guest”. Although we made use of the same object(myString), internally a new object was created in the process. So, if you were to do some string operation involving an append or trim or some other method call to modify your string object, you would really be creating those many new objects of class String.
Now isn’t that a performance issue?
Yes, it definitely is.
Then how do you make your string operations efficient?
By using StringBuffer or StringBuilder.
How would that help?
Well, since StringBuffer/StringBuilder objects are mutable, we can make changes to the value stored in the object. What this effectively means is that string operations such as append would be more efficient if performed using StringBuffer/StringBuilder objects than String objects.
Finally, whats the difference between StringBuffer and StringBuilder?
StringBuffer and StringBuilder have the same methods with one difference and that’s of synchronization. StringBuffer is synchronized( which means it is thread safe and hence you can use it when you implement threads for your methods) whereas StringBuilder is not synchronized( which implies it isn’t thread safe).
So, if you aren’t going to use threading then use the StringBuilder class as it’ll be more efficient than StringBuffer due to the absence of synchronization.
Incase you do not know – Here’s how you use StringBuilder
A simple Example to demonstrate that String object is Immutable
Incase you still have any doubts regarding String or StringBuilder then do leave a comment. I’ll be more than eager to help you out.
Note: StringBuilder was introduced in Java 1.5 (so if you happen to use versions 1.4 or below you’ll have to use StringBuffer)

================================================================================================================================================


Differences between String, StringBuffer and StringBuilder in Java

String in Java

Before looking difference between String and StringBuffer or StringBuilder let’s see some fundamental properties of String Class in Java

string and stringbuffer, string vs stringbuffer vs stringbuilder1) String is immutable in Java:  String is by design immutable in Java you can check this post for reason. Immutability offers lot of benefit to the String class e.g. his hashcode value can be cached which makes it a faster hashmap key and one of the reason why String is a popular key in HashMap. Because String is final it can be safely shared between multiple threads  without any extra synchronization.

2)when we represent string in double quotes like "abcd" they are referred as String literal and String literals are created in String pools. When you compare two String literals using equality operator "==" it returns true because they are actually same instance of String. Anyway comparing object with equality operator is bad practice in Java and you should always use equals method to check equality.

3) "+" operator is overloaded for String and used to concatenated two string. Internally "+" operation is implemented using either StringBuffer or StringBuilder.

4) Strings are backed up by character Array and represented in UTF-16 format. By the way this behavior can cause memory leak in String because same character array is shared between source String and SubString which can prevent source String from being garbage collected. See How SubString works in Java for more details.

5) String class overrides equals() and hashcode() method and two Strings are considered to be equal if they contain exactly same character in same order and in same case. If you want ignore case comparison of two strings consider using equalsIgnoreCase() method. See  how to correctly override equals method in Java  to learn more about best practices on equals method. Another worth noting point is that equals method must be consistent with compareTo() method for String because SortedSet and SortedMap e.g. TreeMap uses compareTo method to compare String in Java.

7) toString() method provides String representation of any object and its declared in Object class and its recommended for other class to implement this and provide String representation.

8) String is represented using UTF-16 format in Java.

9) In Java you can create String from char array, byte array, another string, from StringBuffer or from StringBuilder. Java String class provides constructor for all of these.


Problem with String in Java

difference between String and StringBuffer and StringBuilder, string vs stringbuffer One of its biggest strength Immutability is also biggest problem of Java String if not used correctly. many a times we create a String and then perform a lot of operation on them e.g. converting string into uppercase, lowercase , getting substring out of it , concatenating with other string etc. Since String is an immutable class every time a new String is created and older one is discarded which creates lots of temporary garbage in heap. If String are created using String literal they remain in String pool. To resolve this problem Java provides us two Classes StringBuffer and StringBuilder. String Buffer is an older class but StringBuilder is relatively new and added in JDK 5.


Differences between String and StringBuffer in Java

Main difference between String and StringBuffer is String is immutable while StringBuffer is mutable means you can modify a StringBuffer object once you created it without creating any new object. This mutable property makes StringBuffer an ideal choice for dealing with Strings in Java. You can convert a StringBuffer into String by its toString() method. String vs StringBuffer or what is difference between StringBuffer and String is one of the popular Java interview questions for either phone interview or first round. Now days they also include StringBuilder and ask String vs StringBuffer vs StringBuilder. So be preparing for that. In the next section we will see difference between StringBuffer and StringBuilder in Java.

Difference between StringBuilder and StringBuffer in Java

StringBuffer is very good with mutable String but it has one disadvantage all its public methods are synchronized which makes it thread-safe but same time slow. In JDK 5 they provided similar class called StringBuilder in Java which is a copy of StringBuffer but without synchronization. Try to use StringBuilder whenever possible it performs better in most of cases than StringBuffer class. You can also use "+" for concatenating two string because "+" operation is internal implemented using either StringBuffer or StringBuilder in Java. If you see StringBuilder vs StringBuffer you will find that they are exactly similar and all API methods applicable to StringBuffer are also applicable to StringBuilder in Java. On the other hand String vs StringBuffer is completely different and there API is also completely different, same is true for StringBuilder vs String.

Summary

In summary here are list of difference between StringBuffer, String and StringBuilder in Java :

1) String is immutable while StringBuffer and StringBuilder is mutable object.
2) StringBuffer is synchronized while StringBuilder is not which makes StringBuilder faster than StringBuffer.
3) Concatenation operator "+" is internal implemented using either StringBuffer or StringBuilder.
4) Use String if you require immutability, use Stringbuffer in java if you need mutable + thread-safety and use StringBuilder in Java if you require mutable + without thread-safety.

That's all on famous String vs StringBuffer or StringBuffer vs StringBuilder discussion. All these differences helps to avoid common coding mistake of using String in place of StringBuffer in many places. from Java 5 onwards either use + operator of StringBuilder for concatenating String in Java. 

================================================================================================================================================

The StringBuffer and StringBuilder classes are used when there is a necessity to make alot of modifications to Strings of characters.
Unlike Strings objects of type StringBuffer and Stringbuilder can be modified over and over again with out leaving behind alot of new unused objects.
The StringBuilder class was introduced as of Java 5 and the main difference between the StringBuffer and StringBuilder is that StringBuilders methods are not thread safe(not Synchronised).
It is recommended to use StringBuilder whenever possible because it is faster than StringBuffer. However if thread safety is necessary the best option is StringBuffer objects.

Example:

public class Test{

    public static void main(String args[]){
       StringBuffer sBuffer = new StringBuffer(" test");
       sBuffer.append(" String Buffer");
       System.ou.println(sBuffer);  
   }
}
This would produce following result:
test String Buffer

StringBuffer Methods:

Here is the list of important methods supported by StringBuffer class:
SNMethods with Description
1public StringBuffer append(String s)
Updates the value of the object that invoked the method. The method takes boolean, char, int, long, Strings etc.
2public StringBuffer reverse()
The method reverses the value of the StringBuffer object that invoked the method.
3public delete(int start, int end)
Deletes the string starting from start index until end index.
4public insert(int offset, int i)
This method inserts an string s at the position mentioned by offset.
5replace(int start, int end, String str)
This method replaces the characters in a substring of this StringBuffer with characters in the specified String.
Here is the list of other methods (Except set methods ) which are very similar to String class:
SNMethods with Description
1int capacity()
Returns the current capacity of the String buffer.
2char charAt(int index)
The specified character of the sequence currently represented by the string buffer, as indicated by the index argument, is returned.
3void ensureCapacity(int minimumCapacity)
Ensures that the capacity of the buffer is at least equal to the specified minimum.
4void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
Characters are copied from this string buffer into the destination character array dst.
5int indexOf(String str)
Returns the index within this string of the first occurrence of the specified substring.
6int indexOf(String str, int fromIndex)
Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.
7int lastIndexOf(String str)
Returns the index within this string of the rightmost occurrence of the specified substring.
8int lastIndexOf(String str, int fromIndex)
Returns the index within this string of the last occurrence of the specified substring.
9int length()
Returns the length (character count) of this string buffer.
10void setCharAt(int index, char ch)
The character at the specified index of this string buffer is set to ch.
11void setLength(int newLength)
Sets the length of this String buffer.
12CharSequence subSequence(int start, int end)
Returns a new character sequence that is a subsequence of this sequence.
13String substring(int start)
Returns a new String that contains a subsequence of characters currently contained in this StringBuffer.The substring begins at the specified index and extends to the end of the StringBuffer.
14String substring(int start, int end)
Returns a new String that contains a subsequence of characters currently contained in this StringBuffer.
15String toString()
Converts to a string representing the data in this string buffer.

======================================================================================
 Difference between StringBuilder & StringBuffer
Hello Everyone,
I wanted to know the difference between StringBuilder & StringBuffer classes and thier practical use. So,I wrote 2 code snippets in which I spawn 3 threads simultaneously which make use of StringBuilder & StringBuffer objects. When I run the code, i expect all the 3 threads to run simultaneously in case of StringBuilder & in synchronized manner in case of StringBuffer. But in BOTH the cases, they run in synchronized manner. then what is the use of StringBuffer class?:confused: (In case of String objects, all the 3 threads run simultaneeously). I will share the code snippets for your reference. Please also correct me if I'm wrong in understanding the concept of multi-threading itself. And please, also correct the code.:):)
Thanks In Advance!

// StringBuilder...

public class MultiTread implements Runnable{
private StringBuilder name;
public MultiTread(StringBuilder string){
name=string;
}

public void run(){
for(int i=0; i<=10; i++){
System.out.println(name.append(i));
}
}
public static void main(String[] args){
Thread th = new Thread(new MultiTread(new StringBuilder("thread1:")));
Thread th1 = new Thread(new MultiTread(new StringBuilder("thread2:")));
Thread th2 = new Thread(new MultiTread(new StringBuilder("thread3:")));

th.start();
th1.start();
th2.start();
}
}

..................

//StringBuffer...

public class MultiTreadBuf implements Runnable{
private StringBuffer name;
public MultiTreadBuf(StringBuffer string){
name=string;
}

public void run(){
for(int i=0; i<=10; i++){
System.out.println(name.append(i));
}
}
public static void main(String[] args){
Thread th = new Thread(new MultiTreadBuf(new StringBuffer("thread1:")));
Thread th1 = new Thread(new MultiTreadBuf(new StringBuffer("thread2:")));
Thread th2 = new Thread(new MultiTreadBuf(new StringBuffer("thread3:")));

th.start();
th1.start();
th2.start();
}
}

........

//String....

public class MuiltiTreadStr implements Runnable{
private String name;
public MuiltiTreadStr(String string){
name=string;
}

public void run(){
for(int i=0; i<=10; i++){
System.out.println(name+i);
}
}
public static void main(String[] args){
System.out.println("main begins...");
Thread th = new Thread(new MuiltiTreadStr("thread1:"));
Thread th1 = new Thread(new MuiltiTreadStr("thread2:"));
Thread th2 = new Thread(new MuiltiTreadStr("thread3:"));
System.out.println("spawning 3 threads...");
th.start();
th1.start();
th2.start();
System.out.println("main ends...");
}
}
=========================================================================================================

StringBuilder vs StringBuffer


StringBuilder was introduced in JDK 1.5. What's the difference between StringBuilder and StringBuffer? According to javadoc, StringBuilder is designed as a replacement for StringBuffer in single-threaded usage. Their key differences in simple term:
  • StringBuffer is designed to be thread-safe and all public methods in StringBuffer are synchronized. StringBuilder does not handle thread-safety issue and none of its methods is synchronized.

  • StringBuilder has better performance than StringBuffer under most circumstances.

  • Use the new StringBuilder wherever possible.
Other than that, the two classes are remarkably similar with compatible API. It seems the author just copied StringBuffer.java to StringBuilder.java, removing all occurrences of "synchronized". Here is a little trace left in StringBuilder.readObject method:
?
1
2
3
4
5
/**
* readObject is called to restore the state of the
* StringBuffer from a stream.
*/
private void readObject(java.io.ObjectInputStream s)
Note the above javadoc still refers to StringBuffer where it should be StringBuilder.
2 interesting methods in StringBuilder or StringBuffer are reverse() and equals(Object):
  • reverse() method modifies the current this StringBuilder/StringBuffer, and also returns itself. More details in Reverse a String with StringBuilder or StringBuffer

  • equals(Object) method is not implemented (overridden) in StringBuilder/StringBuffer. So comparing 2 instances of the same content will return false. Also there is no equalsIgnoreCase() method on StringBuilder/StringBuffer. However, toString() is implemented to return a string representing the data in this StringBuilder/StringBuffer.
    
 ================================================================================================================================================

List Of Interview Questions:

  1. Can Java thread object invoke start method twice?
  2. Give the list of Java Object class methods.
  3. Can we call servlet destory() from service()?
  4. Can we override static method?
  5. Can you list serialization methods?
  6. What is the difference between super() and this()?
  7. How to prevent a method from being overridden?
  8. Can we create abstract classes without any abstract methods?
  9. How to destroy the session in servlets?
  10. Can we have static methods in interface?
  11. What is transient variable?
  12. Incase, there is a return at the end of try block, will execute finally block?
  13. What is abstract class or abstract method?
  14. What is default value of a boolean?
  15. When to use LinkedList or ArrayList?
  16. What is daemon thread?
  17. Does each thread in java uses seperate stack?
  18. What is the difference between Enumeration and Iterator?
  19. Find out switch statement output.
  20. Does system.exit() in try block executes finally block?
  21. What is fail-fast in java?
  22. What is final, finally and finalize?
  23. In java, are true and false keywords?
  24. What are the different session tracking methods?
  25. What is the purpose of garbage collection?
  26. What are the types of ResultSet?
  27. What is difference between wait and sleep methods in java?
  28. What is servlet context?
  29. What happens if one of the members in a class does not implement Serializable interface?
  30. What is race condition?
  31. How to get current time in milli seconds?
  32. How can you convert Map to List?
  33. What is strictfp keyword?
  34. What is System.out in Java?
  35. What is difference between ServletOuptputStream and PrintWriter?
  36. What is java static import?
  37. When to use String and StringBuffer?
  38. What is difference between StringBuffer and StringBuilder?
  39. What is wrapper class in java?
  40. Is Iterator a Class?
  41. What is java classpath?
  42. Can a class in java be private?
  43. Is null a keyword in java?
  44. What is the initial state of a thread when it is started?
  45. What is the super class for Exception and Error?
  46. What is Class.forName()?
  47. Can interface be final?
  48. What is the difference between exception and error?
  49. What is default value of a local variables?
  50. What is local class in java?
  51. Can we initialise uninitialized final variable?
  52. Can we declare abstract method as final?
  53. Can we have finally block without catch block?
  54. What is pass by value and pass by reference?
  55. Can we declare main method as private?
  56. What is the difference between preemptive scheduling and time slicing?
  57. Can non-static member classes (Local classes) have static members?
  58. What are the environment variables do we neet to set to run Java?
  59. Can you serialize static fields of a class?
  60. What is the difference between declaring a variable and defining a variable?
  61. Where can we use serialization?
  62. What modifiers are allowed for methods in an Interface?
  63. What is the purpose of Runtime and System class?
  64. Which one is faster? ArrayList or Vector? Why?
  65. What is the difference between static synchronized and synchronized methods?
  66. What is the order of catch blocks when catching more than one exception?
  67. What is the difference between the prefix and postfix forms of the increment(++) operator?
  68. What is hashCode?
  69. What is the difference between Hashtable and HashMap?
  70. What are the restrictions when overriding a method?
  71. What is the use of assert keyword?
  72. What is adapter class?
  73. What is difference between break, continue and return statements?
  74. What is the difference between while and do-while statements?
  75. When does the compiler provides the default constructor?
  76. String Sample Code Examples

No comments:

Post a Comment