Core JAVA

Difference between StringBuilder and StringBuffer in Java

<div dir&equals;"ltr" style&equals;"text-align&colon; justify&semi;">&NewLine;<div class&equals;"separator" style&equals;"clear&colon; right&semi; float&colon; right&semi; margin-bottom&colon; 1em&semi; margin-left&colon; 1em&semi; text-align&colon; center&semi;"><img src&equals;"https&colon;&sol;&sol;dineshonjava&period;com&sol;wp-content&sol;uploads&sol;2017&sol;02&sol;stringbuffer-vs-stringbuilder&period;jpg" width&equals;"320" height&equals;"180" border&equals;"0" &sol;><&sol;div>&NewLine;<p>In this article we are going to discuss difference between StringBuilder and StringBuffer class in java&period; This is one of frequently asked question in <a href&equals;"https&colon;&sol;&sol;dineshonjava&period;com&sol;core-java-interview-questions&sol;">core java interview question<&sol;a>&period; In very short StringBuffer is thread-safe means all methods in StringBuffer class are synchronized but StringBuilder is not thread-safe and both classes are mutable unlike String&period; StringBuffer is available from JDK 1&period;0 but StringBuilder is available from JDK 1&period;5&period; Actually StringBuilder is the copy of StringBuffer without thread safety&period; In java there are three classes related to string manipulation <a href&equals;"https&colon;&sol;&sol;dineshonjava&period;com&sol;differences-between-string-stringbuffer-and-stringbuilder-in-java&sol;">String&comma; StringBuffer and StringBuilder<&sol;a> in the java&period;lang package&period;<&sol;p>&NewLine;<p>Out of these three classes <a href&equals;"https&colon;&sol;&sol;dineshonjava&period;com&sol;why-string-is-immutable-and-final-in-java&sol;">String is immutable by nature<&sol;a>&period; while StringBuilder and StringBuffer are mutable version of String&period; String immutability nature because of many reasons related like Security&comma; String Pool&comma; and Performance&period;<&sol;p>&NewLine;<div style&equals;"background-color&colon; &num;f2f9fc&semi; border&colon; 1px solid &num;c9e6f2&semi; border-radius&colon; 3px&semi; padding&colon; 16px&semi; line-height&colon; 1&period;45&semi;">&NewLine;<p><span style&equals;"color&colon; red&semi; font-size&colon; x-large&semi; text-align&colon; center&semi;"><b>Popular Tutorials<&sol;b><&sol;span><&sol;p>&NewLine;<ul style&equals;"text-align&colon; left&semi;">&NewLine;<li><b><a href&equals;"https&colon;&sol;&sol;dineshonjava&period;com&sol;spring-tutorial&sol;"><em><strong>Spring Tutorial<&sol;strong> <&sol;em><&sol;a><&sol;b><&sol;li>&NewLine;<li><b><a href&equals;"https&colon;&sol;&sol;dineshonjava&period;com&sol;spring-web-mvc-framework-chapter-38&sol;"><strong><em>Spring MVC Web Tutorial <&sol;em><&sol;strong><&sol;a><&sol;b><&sol;li>&NewLine;<li><b><a href&equals;"https&colon;&sol;&sol;dineshonjava&period;com&sol;introduction-to-spring-boot-a-spring-boot-complete-guide&sol;"><strong>Spring Boot Tutorial<&sol;strong> <&sol;a><&sol;b><&sol;li>&NewLine;<li><b><a href&equals;"https&colon;&sol;&sol;dineshonjava&period;com&sol;spring-security-take-baby-step-to-secure&sol;"><em>Spring Security Tutorial<&sol;em><&sol;a><&sol;b><&sol;li>&NewLine;<li><b><a href&equals;"https&colon;&sol;&sol;dineshonjava&period;com&sol;spring-aop-tutorial-with-example-aspect-advice-pointcut-joinpoint&sol;"><em>Spring AOP Tutorial<&sol;em><&sol;a><&sol;b><&sol;li>&NewLine;<li><b><a href&equals;"https&colon;&sol;&sol;dineshonjava&period;com&sol;using-spring-jdbc-framework-chapter-32&sol;"><em>Spring JDBC Tutorial<&sol;em><&sol;a><&sol;b><&sol;li>&NewLine;<li><b><a href&equals;"https&colon;&sol;&sol;dineshonjava&period;com&sol;spring-hateoas-hypermedia-driven-restful-web-service&sol;"><em><strong>Spring HATEOAS <&sol;strong><&sol;em><&sol;a><&sol;b><&sol;li>&NewLine;<li><b><a href&equals;"https&colon;&sol;&sol;dineshonjava&period;com&sol;microservices-with-spring-boot&sol;"><em><strong>Microservices with Spring Boot<&sol;strong><&sol;em><&sol;a><&sol;b><&sol;li>&NewLine;<li><b><a href&equals;"https&colon;&sol;&sol;dineshonjava&period;com&sol;jax-rs-web-service-tutorial&sol;"><strong><em>REST Webservice<&sol;em> <&sol;strong><&sol;a><&sol;b><&sol;li>&NewLine;<li><b><a href&equals;"https&colon;&sol;&sol;dineshonjava&period;com&sol;core-java-baby-step-to-be-best-java-ian&sol;"><em><strong>Core Java <&sol;strong><&sol;em><&sol;a><&sol;b><&sol;li>&NewLine;<li><b><a href&equals;"https&colon;&sol;&sol;dineshonjava&period;com&sol;hibernate-3-on-baby-steps&sol;"><em><strong>Hibernate Tutorial<&sol;strong><&sol;em><&sol;a><&sol;b><&sol;li>&NewLine;<li><b><a href&equals;"https&colon;&sol;&sol;dineshonjava&period;com&sol;spring-batch-process-with-example&sol;"><strong><em>Spring Batch<&sol;em> <&sol;strong><&sol;a><&sol;b><&sol;li>&NewLine;<&sol;ul>&NewLine;<&sol;div>&NewLine;<h2><b>Difference between StringBuffer and StringBuilder in Java<&sol;b><&sol;h2>&NewLine;<p>StringBuffer and StringBuilder classes are mutable version of String class&period; They all have common methods for string manipulation in spite of this they have difference in uses in java application&period; Before going to differences let&&num;8217&semi;s discuss some words about both classes from java documents&period;<&sol;p>&NewLine;<h3><b>StringBuffer class<&sol;b><&sol;h3>&NewLine;<p>A thread-safe&comma; mutable sequence of characters&period; A string buffer is like a String&comma; but can be modified&period; At any point in time it contains some particular sequence of characters&comma; but the length and content of the sequence can be changed through certain method calls&period;<&sol;p>&NewLine;<p>String buffers are safe for use by multiple threads&period; The methods are synchronized where necessary so that all the operations on any particular instance behave as if they occur in some serial order that is consistent with the order of the method calls made by each of the individual threads involved&period;<&sol;p>&NewLine;<pre class&equals;"highlight">public synchronized int length&lpar;&rpar; &lbrace; &NewLine; return count&semi; &NewLine; &rcub; &NewLine; &NewLine; public synchronized int capacity&lpar;&rpar; &lbrace; &NewLine; return value&period;length&semi; &NewLine; &rcub; &NewLine; &NewLine; &NewLine; public synchronized void ensureCapacity&lpar;int minimumCapacity&rpar; &lbrace; &NewLine; if &lpar;minimumCapacity &gt&semi; value&period;length&rpar; &lbrace; &NewLine; expandCapacity&lpar;minimumCapacity&rpar;&semi; &NewLine; &rcub; &NewLine; &rcub; &NewLine; &NewLine; &sol;&ast;&ast; &NewLine; &ast; &commat;since 1&period;5 &NewLine; &ast;&sol; &NewLine; public synchronized void trimToSize&lpar;&rpar; &lbrace; &NewLine; super&period;trimToSize&lpar;&rpar;&semi; &NewLine; &rcub; &NewLine; &NewLine; &sol;&ast;&ast; &NewLine; &ast; &commat;throws IndexOutOfBoundsException &lbrace;&commat;inheritDoc&rcub; &NewLine; &ast; &commat;see &num;length&lpar;&rpar; &NewLine; &ast;&sol; &NewLine; public synchronized void setLength&lpar;int newLength&rpar; &lbrace; &NewLine; super&period;setLength&lpar;newLength&rpar;&semi; &NewLine; &rcub; &NewLine; &NewLine; &sol;&ast;&ast; &NewLine; &ast; &commat;throws IndexOutOfBoundsException &lbrace;&commat;inheritDoc&rcub; &NewLine; &ast; &commat;see &num;length&lpar;&rpar; &NewLine; &ast;&sol; &NewLine; public synchronized char charAt&lpar;int index&rpar; &lbrace; &NewLine; if &lpar;&lpar;index &lt&semi; 0&rpar; &vert;&vert; &lpar;index &gt&semi;&equals; count&rpar;&rpar; &NewLine; throw new StringIndexOutOfBoundsException&lpar;index&rpar;&semi; &NewLine; return value&lbrack;index&rsqb;&semi; &NewLine; &rcub; &NewLine; &NewLine;&sol;&sol;Many more methods&period;&period;&period;&period;&period; &NewLine; &NewLine;<&sol;pre>&NewLine;<h3><b>StringBuilder class<&sol;b><&sol;h3>&NewLine;<p>A mutable sequence of characters&period; This class provides an API compatible with StringBuffer&comma; but with no guarantee of synchronization&period; This class is designed for use as a drop-in replacement for StringBuffer in places where the string buffer was being used by a single thread &lpar;as is generally the case&rpar;&period; Where possible&comma; it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations&period;<&sol;p>&NewLine;<pre class&equals;"highlight">public StringBuilder append&lpar;Object obj&rpar; &lbrace; &NewLine; return append&lpar;String&period;valueOf&lpar;obj&rpar;&rpar;&semi; &NewLine; &rcub; &NewLine; &NewLine; public StringBuilder append&lpar;String str&rpar; &lbrace; &NewLine; super&period;append&lpar;str&rpar;&semi; &NewLine; return this&semi; &NewLine; &rcub; &NewLine; &NewLine; &sol;&sol; Appends the specified string builder to this sequence&period; &NewLine; private StringBuilder append&lpar;StringBuilder sb&rpar; &lbrace; &NewLine; if &lpar;sb &equals;&equals; null&rpar; &NewLine; return append&lpar;"null"&rpar;&semi; &NewLine; int len &equals; sb&period;length&lpar;&rpar;&semi; &NewLine; int newcount &equals; count &plus; len&semi; &NewLine; if &lpar;newcount &gt&semi; value&period;length&rpar; &NewLine; expandCapacity&lpar;newcount&rpar;&semi; &NewLine; sb&period;getChars&lpar;0&comma; len&comma; value&comma; count&rpar;&semi; &NewLine; count &equals; newcount&semi; &NewLine; return this&semi; &NewLine; &rcub; &NewLine; &NewLine; &sol;&ast;&ast; &NewLine; &ast; &commat;throws StringIndexOutOfBoundsException &lbrace;&commat;inheritDoc&rcub; &NewLine; &ast;&sol; &NewLine; public StringBuilder delete&lpar;int start&comma; int end&rpar; &lbrace; &NewLine; super&period;delete&lpar;start&comma; end&rpar;&semi; &NewLine; return this&semi; &NewLine; &rcub; &NewLine; &NewLine; &sol;&ast;&ast; &NewLine; &ast; &commat;throws StringIndexOutOfBoundsException &lbrace;&commat;inheritDoc&rcub; &NewLine; &ast;&sol; &NewLine; public StringBuilder deleteCharAt&lpar;int index&rpar; &lbrace; &NewLine; super&period;deleteCharAt&lpar;index&rpar;&semi; &NewLine; return this&semi; &NewLine; &rcub; &NewLine; &NewLine; &sol;&ast;&ast; &NewLine; &ast; &commat;throws StringIndexOutOfBoundsException &lbrace;&commat;inheritDoc&rcub; &NewLine; &ast;&sol; &NewLine; public StringBuilder replace&lpar;int start&comma; int end&comma; String str&rpar; &lbrace; &NewLine; super&period;replace&lpar;start&comma; end&comma; str&rpar;&semi; &NewLine; return this&semi; &NewLine; &rcub; &NewLine; &NewLine; &sol;&ast;&ast; &NewLine; &ast; &commat;throws StringIndexOutOfBoundsException &lbrace;&commat;inheritDoc&rcub; &NewLine; &ast;&sol; &NewLine; public StringBuilder insert&lpar;int index&comma; char str&lbrack;&rsqb;&comma; int offset&comma; &NewLine; int len&rpar; &NewLine; &lbrace; &NewLine; super&period;insert&lpar;index&comma; str&comma; offset&comma; len&rpar;&semi; &NewLine; return this&semi; &NewLine; &rcub; &NewLine; &NewLine;&sol;&sol;Many more methods&period;&period;&period;&period;&period; &NewLine; &NewLine;<&sol;pre>&NewLine;<h2><b>StringBuider vs StringBuffer<&sol;b><&sol;h2>&NewLine;<p>There are following are main difference between StringBuffer and StringBuilder in Java<&sol;p>&NewLine;<p><b>Synchronization<&sol;b><br &sol;>&NewLine;All Methods in StringBuffer class are synchronized but StringBuilder is non synchronized&period; In short StringBuilder unsynchronized version of StringBuffer class&period; You can not share Instances of StringBuilder class between multiple threads&period; If such synchronization is required then it is better to use StringBuffer class&period;<br &sol;>&NewLine;<b><br &sol;>&NewLine;<&sol;b> <b>Performance<&sol;b><br &sol;>&NewLine;Due thread-safe nature of StringBuffer make it slower than StringBuilder because of StringBuffer has overhead of acquiring and releasing locks associated with synchronized methods&period;<&sol;p>&NewLine;<p><b>From which java version<&sol;b><br &sol;>&NewLine;StringBuffer is available from JDK 1&period;0 but StringBuilder is available from JDK 1&period;5&period;<&sol;p>&NewLine;<p><b>Which one to use and when<&sol;b><br &sol;>&NewLine;StringBuffer and StringBuilder are almost same&comma; both classes have same methods but StringBuffer has synchronized methods due to thread-safety&period; So that means if thread-safety is matter and performance is not matter for any operation then we should use StringBuffer instead of StringBuilder&period; There some areas in the application where performance is matter without thread safety then StringBuilder could be used&period; In short if you think that the operation should be thread-safe then use StringBuffer&comma; in all other cases StringBuilder is a better choice as it offers you the same functionality with better performance&period;<&sol;p>&NewLine;<p><b>Interested Point about String Concatenation<&sol;b><br &sol;>&NewLine;Suppose you want concatenate two or more strings using &plus; operator&comma; Java internally convert that operator call to corresponding StringBuilder append&lpar;&rpar; method&period; For example there are three string literals &&num;8220&semi;Dinesh&&num;8221&semi;&comma; &&num;8221&semi; on &&num;8221&semi; &comma; &&num;8220&semi;Java&&num;8221&semi; if want to add these three literal to make final string &&num;8220&semi;Dinesh on Java&&num;8221&semi; then we can concatenate these as &&num;8220&semi;Dinesh&&num;8221&semi; &plus; &&num;8221&semi; on &&num;8221&semi; &plus; &&num;8220&semi;Java&&num;8221&semi;&comma; that will be converted to new StringBuilder&lpar;&rpar;&period;append&lpar;&&num;8220&semi;Dinesh&&num;8221&semi;&rpar;&period;append&lpar;&&num;8221&semi; on &&num;8220&semi;&rpar;&period;append&lpar;&&num;8220&semi;Java&&num;8221&semi;&rpar;&period; Only problem is that it initialize StringBuilder with default capacity&comma; which means expensive array copy operation&comma; when StringBuilder get resized&period; So be careful whenever you want to concatenation of strings&comma; in this case always use StringBuilder or StringBuffer&period;<&sol;p>&NewLine;<h2><b>Summary<&sol;b><&sol;h2>&NewLine;<p>In this article we have seen the basic features and some differences of StringBuffer and StringBuilder&period; StringBuffer and String class both are from Java first version but StringBuilder added from Java 5&period; StringBuffer and StringBuilder both classes are mutable unlike String is immutable&period; StringBuffer is thread-safe in nature i&period;e&period; all methods of this class are synchronized&period; But StringBuilder is simply unsynchronized copy of StringBuffer class&period;<&sol;p>&NewLine;<div style&equals;"background-color&colon; &num;f2f9fc&semi; border-radius&colon; 3px&semi; border&colon; 1px solid &num;c9e6f2&semi; line-height&colon; 1&period;45&semi; padding&colon; 16px&semi;">&NewLine;<p><b>String Related Posts<&sol;b><&sol;p>&NewLine;<ol style&equals;"text-align&colon; left&semi;">&NewLine;<li><b><a href&equals;"https&colon;&sol;&sol;dineshonjava&period;com&sol;how-to-make-java-class-immutable&sol;">How to make Immutable Class in Java<&sol;a><&sol;b><&sol;li>&NewLine;<li><b><a href&equals;"https&colon;&sol;&sol;dineshonjava&period;com&sol;core-java-interview-questions&sol;">Core Java Interview Questions<&sol;a><&sol;b><&sol;li>&NewLine;<li><b><a href&equals;"https&colon;&sol;&sol;dineshonjava&period;com&sol;string-class-in-java&sol;">String Class in Java<&sol;a><&sol;b><&sol;li>&NewLine;<li><b><a href&equals;"https&colon;&sol;&sol;dineshonjava&period;com&sol;why-string-is-immutable-and-final-in-java&sol;">Why String is Immutable and Final in Java<&sol;a><&sol;b><&sol;li>&NewLine;<li><b><a href&equals;"https&colon;&sol;&sol;dineshonjava&period;com&sol;convert-string-to-integer-to-string-in-java-with-example&sol;">Convert String to Integer to String in Java with Example<&sol;a><&sol;b><&sol;li>&NewLine;<li><b><a href&equals;"https&colon;&sol;&sol;dineshonjava&period;com&sol;convert-double-to-string-to-double-in-java-with-example&sol;">Convert Double to String to Double in Java with Example<&sol;a><&sol;b><&sol;li>&NewLine;<li><b><a href&equals;"https&colon;&sol;&sol;dineshonjava&period;com&sol;convert-date-to-string-in-java-with-example&sol;">Convert Date to String in Java with Example<&sol;a><&sol;b><&sol;li>&NewLine;<li><b><a href&equals;"https&colon;&sol;&sol;dineshonjava&period;com&sol;differences-between-string-stringbuffer-and-stringbuilder-in-java&sol;">Differences between String&comma; StringBuffer and StringBuilder in Java<&sol;a><&sol;b><&sol;li>&NewLine;<li><b><a href&equals;"https&colon;&sol;&sol;dineshonjava&period;com&sol;difference-between-stringbuilder-and-stringbuffer-in-java&sol;">Differences StringBuffer and StringBuilder<&sol;a><&sol;b><&sol;li>&NewLine;<li><b><a href&equals;"https&colon;&sol;&sol;dineshonjava&period;com&sol;how-to-compare-two-strings-in-java&sol;">How to Compare two Strings in Java<&sol;a><&sol;b><&sol;li>&NewLine;<li><b><a href&equals;"https&colon;&sol;&sol;dineshonjava&period;com&sol;hashcode-and-equals-methods-in-java&sol;">Difference between hashCode&lpar;&rpar; and equals&lpar;&rpar; methods in Java<br &sol;>&NewLine;<&sol;a><&sol;b><&sol;li>&NewLine;<li><b><a href&equals;"https&colon;&sol;&sol;dineshonjava&period;com&sol;java-string-substring-method&sol;"> Java &&num;8211&semi; String substring&lpar;&rpar; Method<br &sol;>&NewLine;<&sol;a><&sol;b><&sol;li>&NewLine;<li><b><a href&equals;"https&colon;&sol;&sol;dineshonjava&period;com&sol;difference-between-wait-and-sleep&sol;"> Difference between wait&lpar;&rpar; and sleep&lpar;&rpar;<br &sol;>&NewLine;<&sol;a><&sol;b><&sol;li>&NewLine;<&sol;ol>&NewLine;<&sol;div>&NewLine;<&sol;div>&NewLine;<div class&equals;"wp-post-navigation"> &NewLine;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab; <div class&equals;"wp-post-navigation-pre"> &NewLine;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab; <a href&equals;"https&colon;&sol;&sol;dineshonjava&period;com&sol;differences-between-string-stringbuffer-and-stringbuilder-in-java&sol;">Previous<&sol;a> &NewLine;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab; <&sol;div> &NewLine;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab; <div class&equals;"wp-post-navigation-next"> &NewLine;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab; <a href&equals;"https&colon;&sol;&sol;dineshonjava&period;com&sol;how-to-compare-two-strings-in-java&sol;">Next<&sol;a> &NewLine;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab; <&sol;div> &NewLine;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;<&sol;div>&NewLine;<script type&equals;"text&sol;javascript">&NewLine;jQuery&lpar;document&rpar;&period;ready&lpar;function&lpar;&dollar;&rpar; &lbrace;&NewLine; &dollar;&period;post&lpar;'https&colon;&sol;&sol;dineshonjava&period;com&sol;wp-admin&sol;admin-ajax&period;php'&comma; &lbrace;action&colon; 'mts&lowbar;view&lowbar;count'&comma; id&colon; '69'&rcub;&rpar;&semi;&NewLine;&rcub;&rpar;&semi;&NewLine;<&sol;script>

Dinesh Rajput

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture. He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Share
Published by
Dinesh Rajput

Recent Posts

Strategy Design PatternsĀ using Lambda

Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…

4 years ago

Decorator Pattern using Lambda

Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…

4 years ago

Delegating pattern using lambda

Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…

4 years ago

Spring Vs Django- Know The Difference Between The Two

Technology has emerged a lot in the last decade, and now we have artificial intelligence;…

4 years ago

TOP 20 MongoDB INTERVIEW QUESTIONS 2022

Managing a database is becoming increasingly complex now due to the vast amount of data…

4 years ago

Scheduler @Scheduled Annotation Spring Boot

Overview In this article, we will explore Spring Scheduler how we could use it by…

4 years ago