Movatterモバイル変換


[0]ホーム

URL:


Difference between StringBuilder and StringBuffer in Java with Example

If you are in a hurry and heading straight to interview then I won't take much of your time, In a couple of words, the main difference between StringBuffer and StringBuilder is between four parameters,synchronization,speed,thread-safety, andavailability.StringBufferis synchronized and that's why thread-safe, butStringBuilderis not synchronized, not thread-safe and that's why fast. Regarding availability,StringBufferis available from Java 1.0 whileStringBuilder was added in Java 5. 

Now we can take a breath, and can continue with rest of this article. In Java, there are three classes to deal with String data type,String,StringBufferandStringBuilder. All of three belongs tojava.lang package, which is automatically imported into every Java program thus you don't need to do any import for usingStringBuilderandStringBuffer.

Out of these three,String is immutable in Java, whileStringBuilderandStringBufferare mutable version of String. Some one with little bit of common sense will think that, why do one need three classes for same functionality, why can'tStringjust do whatStringBuilderandStringBuffer does.

This definitely would have required keeping String mutable, which is not favorable to Java designers for many reasons, like Security, String Pool, and Performance. So designers of Java API has introduced a pattern of providing a mutable companion class for immutable main class.




Difference between StringBuffer and StringBuilder in Java 

Though both of these classes are a mutable versions of String class, there is one significant difference between them, which makes this question interesting and favorite among Java interviewers. More often than not, I see this question coming up intelephonic round of Java interviews or even a couple of rounds of a preliminary face-to-face interview.


1. StringBuffer is Synchronized and StringBuilder is Not
Yes, this is the common answer from a majority of Java developers to this question, which is true, but when asked to elaborate this answer, most of them fail miserably. In order to elaborate, you must know what is meant by synchronized and what changes StringBuilder make to achieve that. 

In this case it's pretty straightforward. If you open code ofStringBuffer.java andStringBuilder.java , you can do this in Eclipse IDE by pressingCtrl + T and typingStringBufferfor former andStringBuilderfor later. 

This is one of theseveral useful Eclipse short-cuts discussed in that article.  Almost all the methods of StringBuffer e.g.length(),capacity(),ensureCapacity() ,setLength(),charAt() and all overloaded version ofappend() methods are synchronized, as shown below :

public StringBuffer(CharSequence seq) {        this(seq.length()+ 16);        append(seq);    }publicsynchronizedint length() {return count;    }publicsynchronizedint capacity() {return value.length;    }publicsynchronizedvoid ensureCapacity(int minimumCapacity) {if (minimumCapacity> value.length) {            expandCapacity(minimumCapacity);        }    }/**     *@since      1.5     */publicsynchronizedvoid trimToSize() {        super.trimToSize(); 
    }

This is done to protect instance variable likecount,value (character array which holds the content of StringBuffer) being corrupted by exposing to multiple threads. In fact, every method which touches these variables are madesynchronized, which is of course absolutely needed if you want to makeStringBuffer thread-safe, but as a side effect, this makesStringBufferinstances slower. 




On the other hand, if you look atStringBuiderclass, you will not find any single synchronized method.  If you don't believe me do a search for a synchronized word inStringBuilder.java file. All corresponding methods in this class are non-synchronized.

publicStringBuilder append(char[] str,int offset,int len) {        super.append(str, offset, len);return this;    }publicStringBuilder append(boolean b) {        super.append(b);return this;    }publicStringBuilder append(char c) {        super.append(c);return this;    }publicStringBuilder append(int i) {        super.append(i);return this;    }publicStringBuilder append(long lng) {        super.append(lng);return this;    }publicStringBuilder append(float f) {        super.append(f);return this;    }

One more thing to note about StringBuffer and StringBuilder is that they inherit from a common parent class, AbstractStringBuilder. This is anabstract class, which also implementsAppendableandCharSequenceinterface. This was introduced in Java 1.5 to bringStringBufferandStringBuilder into the same type hierarchy. 

This class represents a mutable sequence of characters. At any point in time, it contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls like append()

StringBuffer overrides almost every method to add synchronized keyword on it, but apparently doesn't use @Override annotation. I really found this amusing because annotation was also introduced on same release but they didn't they could have added those inStringBufferclass to make it more readable.

2) Anotherdifference between StringBuffer and StringBuilder is that former is thread-safe and later is not. You can share instance of StringBuffer between multiple thread without any external synchronization, but its not safe to share instance ofStringBuilderlike that. If you ever need to use a mutable String between multiple thread, go forStringBuffer, for all local use, which is within inside one thread, use StringBuilder.

3) Third difference betweenStringBuilderandStringBufferalso stem from same fact, becauseStringBufferis synchronized and thread-safe its bound to be slower than its non-synchronized, non-thread-safe counterpart StringBuilder, because of time taken to acquire and release lock while calling methods ofStringBuffer.

In short, if you have good knowledge of Java programming language, you can actually deduce all three differences from just one fact that,StringBuffer is synchronized while StringBuilder is not. In fact, that will impress interviewer more, because apart from answering the question it also demonstrate your sound knowledge of Java programming language. 

Always take this kind of opportunities and demonstrate your talent and deep understanding of subject during interviews. It's a proven strategy to do well on interviews.




StringBuider vs StringBuffer in Java? When to use StringBuilder?

In summary, the following are the notable difference between StringBuffer and StringBuilder in Java:

1. StringBuilder is a non synchronized version ofStringBufferclass. Methods in
StringBuilder
like all overloaded version ofappend() method is not synchronized.

2. StringBuilder is definitely faster than StringBuffer because of no overhead of acquiring and releasing locks associated with synchronized methods.

3. StringBuffer is thread-safe and StringBuilder is not. You can not share the Instances of the StringBuilder class between multiple threads. If such synchronization is required then it is better to use the StringBuffer class.

4. StringBuffer is an old class, its there in JDK from very first release, while StringBuilder is relatively newer class, introduced much later in the release of JDK 1.5

5. Another interesting fact to know about both of this class is that, when you doStringconcatenation using + operator, Java internally convert that call to correspondingStringBuilderappend() method class. 

For example"one" + "two" + "three" will be converted to newStringBuilder().append("one").append("two").append("three"). Only problem is that it initializesStringBuilderwith default capacity, which means expensive array copy operation whenStringBuilderget resized.

Difference between StringBuilder and StringBuffer in Java [Answer]



That's all about the difference between StringBuffer and StringBuilder in Java. You just can't afford to miss this question. The good thing about this question is that it provides you an opportunity to show your knowledge about how synchronization, thread-safety, and speed are related to each other. It also demonstrates your sound knowledge of Java API and how much you know about its evolution in every version, but the most important thing is to learn when to use StringBuilder and StringBuffer class. 

Difference between StringBuffer and StringBuilder in JavaSince every Java program makes extensive use of both immutable and mutable String, you must know the difference betweenStringBuilderandStringBufferto make right use of them. By default, you should always use StringBuilder and only consider or StringBuffer when you see that a mutable string must be shared between multiple threads.


Do you want more interview questions related to String? Check out these interesting posts :
  • How to reverse String in Java without using StringBuffer? (Solution)
  • How to replace characters from String in Java?  (Answer)
  • How to check if two String are anagram to each other?  (Solution)
  • How to check if a String contains another SubString?  (Answer)
  • How to remove white-space from String in Java?  (Answer)
  • How to convert String to Integer in Java?  (Solution)
  • How to escape XML special characters in Java?  (Solution)
  • What does matches method do in String class?(Solution)
  • How to format Date to String in Java?  (Answer)
  • How to convert String to Enum in Java? (Answer)
  • Difference between String and StringBuffer in Java? (Answer)

Thanks for reading this article so far. Knowing the difference between StringBuffer and StringBuider is quite important for Java developer as they are essential classes and incorrect use of them can degrade performance of Java application by triggering excessive and unnecessary garbage collection due to lots of temporary objects.

2 comments:

Feel free to comment, ask questions if you have any doubt.


[8]ページ先頭

©2009-2025 Movatter.jp