AUGUSTEN TECHNICAL

FRESHERS SHINE

Pages

Friday 27 June 2014

Difference between StringBuilder and StringBuffer in Java

If you are in hurry and heading straight to interview then I won't take much of your time, In couple of words, main difference between StringBuffer and StringBuilder is between four parameters, synchronization, speed,thread-safety and availability.StringBuffer is synchronized and that's why thread-safe, but StringBuilder is not synchronized, not thread-safe and that's why fast. Regarding availability, StringBuffer is available from Java 1.0 while StringBuilderwas added on 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, StringBuffer and StringBuilder. All of three belongs to java.langpackage, which is automatically imported to every Java program thus you don't need to do any import for using StringBuilder and StringBuffer. Out of these three, String is immutable in Java, while StringBuilder and StringBuffer are 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't String just do what StringBuilder and StringBuffer does. This definitely would have required keeping String mutable, which is not favourable 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. StringBuffer was introduced along with String from very first version of Java API, the JDK 1.0, while StringBuilder was introduce quite late in early 2000s when Java 1.5 was released.

0 comments:

Post a Comment