Explore Courses
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Birla Institute of Management Technology Birla Institute of Management Technology Post Graduate Diploma in Management (BIMTECH)
  • 24 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Popular
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science & AI (Executive)
  • 12 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
University of MarylandIIIT BangalorePost Graduate Certificate in Data Science & AI (Executive)
  • 8-8.5 Months
upGradupGradData Science Bootcamp with AI
  • 6 months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
OP Jindal Global UniversityOP Jindal Global UniversityMaster of Design in User Experience Design
  • 12 Months
Popular
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Rushford, GenevaRushford Business SchoolDBA Doctorate in Technology (Computer Science)
  • 36 Months
IIIT BangaloreIIIT BangaloreCloud Computing and DevOps Program (Executive)
  • 8 Months
New
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Popular
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
Golden Gate University Golden Gate University Doctor of Business Administration in Digital Leadership
  • 36 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
Popular
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
Bestseller
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
IIIT BangaloreIIIT BangalorePost Graduate Certificate in Machine Learning & Deep Learning (Executive)
  • 8 Months
Bestseller
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in AI and Emerging Technologies (Blended Learning Program)
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
ESGCI, ParisESGCI, ParisDoctorate of Business Administration (DBA) from ESGCI, Paris
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration From Golden Gate University, San Francisco
  • 36 Months
Rushford Business SchoolRushford Business SchoolDoctor of Business Administration from Rushford Business School, Switzerland)
  • 36 Months
Edgewood CollegeEdgewood CollegeDoctorate of Business Administration from Edgewood College
  • 24 Months
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with Concentration in Generative AI
  • 36 Months
Golden Gate University Golden Gate University DBA in Digital Leadership from Golden Gate University, San Francisco
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Deakin Business School and Institute of Management Technology, GhaziabadDeakin Business School and IMT, GhaziabadMBA (Master of Business Administration)
  • 12 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science (Executive)
  • 12 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityO.P.Jindal Global University
  • 12 Months
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (AI/ML)
  • 36 Months
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDBA Specialisation in AI & ML
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
New
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGrad KnowledgeHutupGrad KnowledgeHutAzure Administrator Certification (AZ-104)
  • 24 Hours
KnowledgeHut upGradKnowledgeHut upGradAWS Cloud Practioner Essentials Certification
  • 1 Week
KnowledgeHut upGradKnowledgeHut upGradAzure Data Engineering Training (DP-203)
  • 1 Week
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
Loyola Institute of Business Administration (LIBA)Loyola Institute of Business Administration (LIBA)Executive PG Programme in Human Resource Management
  • 11 Months
Popular
Goa Institute of ManagementGoa Institute of ManagementExecutive PG Program in Healthcare Management
  • 11 Months
IMT GhaziabadIMT GhaziabadAdvanced General Management Program
  • 11 Months
Golden Gate UniversityGolden Gate UniversityProfessional Certificate in Global Business Management
  • 6-8 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
IU, GermanyIU, GermanyMaster of Business Administration (90 ECTS)
  • 18 Months
Bestseller
IU, GermanyIU, GermanyMaster in International Management (120 ECTS)
  • 24 Months
Popular
IU, GermanyIU, GermanyB.Sc. Computer Science (180 ECTS)
  • 36 Months
Clark UniversityClark UniversityMaster of Business Administration
  • 23 Months
New
Golden Gate UniversityGolden Gate UniversityMaster of Business Administration
  • 20 Months
Clark University, USClark University, USMS in Project Management
  • 20 Months
New
Edgewood CollegeEdgewood CollegeMaster of Business Administration
  • 23 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
KnowledgeHut upGradKnowledgeHut upGradBackend Development Bootcamp
  • Self-Paced
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 5 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
upGradupGradDigital Marketing Accelerator Program
  • 05 Months

StringBuffer vs. StringBuilder: Difference Between StringBuffer & StringBuilder

Updated on 02 June, 2023

14.04K+ views
9 min read

When programming in Java, Strings are one of the most used classes. A String is an object which is used when you want to represent a sequence of characters. They have several properties, and one of them is immutability, which means that they cannot be modified. String Buffers and String Builders were introduced in Java to tackle this. Using these classes, modifications can be done over and over again.

In this article, We’ll be going through both these classes and discussing the differences between them. Before diving into the classes, we shall familiarize ourselves with the concept of strings in Java.

Check out our free courses to get an edge over the competition.

Strings in Java

Strings are used in Java to store a sequence of character values. They are treated as objects in the Java programming language. We have various options to create and manipulate strings.

To create a string, the basic syntax is as follows:

String sentence = “Hello, world!”;

Strings have some properties, and one of them is that they are immutable, which means that they cannot be modified. But what if you want a string that can be modified. To do so, Java modifications called String Buffers and String Builders are used. Now that we have an understanding of what strings are, we shall proceed with our comparison.

Must Read: Java Project Ideas & Topics

Learn Software Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.

Check out upGrad’s Java Bootcamp.

StringBuffer

String Buffer is a class modification used in Java to add more functionality to the strings by giving characteristics like mutability. We can use methods like append(), insert(), reverse(), replace(), etc. to modify strings. StringBuffer has four defined constructors; they are as follows:

  • StringBuffer(): This creates an empty string buffer with no characteristics with 16 characters’ capacity.
  • StringBuffer(CharSequence chars): It creates a StringBuffer containing the same characters as the specified CharSequence.
  • StringBuffer(int size): This constructs a StringBuffer with no characters with a specified initial capacity.
  • StringBuffer(String str): It creates a StringBuffer object with an initially specified string.

Check out upGrad’s Advanced Certification in DevOps

Let us discuss some of the different methods we can use in StringBuffer to modify a particular string:

  • Length () and capacity(): The current length of a StringBuffer can be found with the help of length() method while to find the total capacity, we use capacity() method.
  • append(): The append() method is used to concatenate the string with other or similar data types. We can append strings, numbers, and objects to a string using this method.
  • Insert (): This method is used to insert one string into another string.
  • charAt(): This method is used to find the value of a single character in a StringBuffer.

We can see how we can use StringBuffer to modify strings according to our needs. So why do we use StringBuilder when we can get such functionality with StringBuffer?

Learn: Top 20 Trending Android Project Ideas & Topics For Beginners

StringBuilder

StringBuilder in Java is a sequence of mutable characters. StringBuilder provides an alternate class to make strings that can be modified as we know that strings are immutable. It is very similar to StringBuffer, but where these two differ is in the synchronization. StringBuilder is not synchronized, which in turn means it is not thread-safe. StringBuilder also has four defined constructors; they are as follows:

  • StringBuilder(): It creates an empty StringBuilder with a room for 16 characters.
  • StringBuilder(int size): It makes an empty string with a specified size.
  • StringBuilder(CharSequence seq): It creates a StringBuilder containing the same characters as the specified CharSequence.
  • StringBuilder(String str): Creates a String Builder object with an initially specified string str.

Let us discuss some of the methods we can use on StringBuilders:

  • append(): This method is used when you want to append something to the string whether it is a string or a number or an object.
  • Replace (): If you’re going to replace a string of characters from another set of characters, you can use the replace() method.
  • Substring (): If you’re going to get a portion of a string you can obtain it by using the substring() method.

So as we can see that StringBuffer and StringBuilder seem to be the same. Even though they have similar functionality, they are quite different, and you might be better off using one rather than the other in many cases.

Differences between the two classes

Synchronization

By default, the StringBuffer is synchronized, whereas StringBuilder doesn’t have any synchronization. In cases where the string has to be accessed by multiple threads and no external synchronization is applied, you must use StringBuffer and not StringBuilder.

Thread-safe

StringBuilder is not a thread-safe class, whereas StringBuffer has this characteristic; this is due to the fact that StringBuffer is synchronized.

Speed

Due to the above two characteristics, StringBuffer is slower compared to StringBuilder. So if you want to have faster performance and don’t require the above characteristics, StringBuilder’s speed and efficiency make it a better choice.

 StringBuilder wad introduced in Java 1.5 by analyzing StringBuffer’s shortcoming and has enough changes that make it viable to use in certain situations where the former might take a hit on the performance.

Performance and Memory Consumption

As we can learn from the points above, StringBuilder is faster when it comes to performance compared to StringBuffer. Memory Consumption among the two is also different where StringBuffer consumes more memory compared to the latter.

Also Read: Top 130+ Java Interview Questions & Answers

Stringbuffer vs Stringbuilder

When several character-based String alterations are required, the StringBuffer and StringBuilder classes are employed. To know when to use what, we need to know Java StringBuilder vs. StringBuffer thoroughly.

Example of String Buffer

class Example_String_Buffer{  
public static void main(String args[]){  
StringBuffer sbe=new StringBuffer(“Lorem”);  
sbe.append(“Ipsum”); 
System.out.println(sbe);  
} }

Output – 

Lorem Ipsum

Example of StringBuilder

class Example_String_Builder{  
public static void main(String args[]){  
StringBuilder sbr=new StringBuilder(“Lorem”);  
sbe.append(“Ipsum”); 
System.out.println(sbr);  
} }

Output – 

Lorem Ipsum

Conversion Between Types Of Strings In Java

To better understand the difference between StringBuffer and StringBuilder, we also need to know their conversions. Techniques to convert a string object of different classes like StringBuffer, StringBuilder, and String to one another are as follows: 

  • From StringBuffer to StringBuilder or vice-versa.
  • From String to StringBuffer and StringBuilder. 
  • From StringBuffer and StringBuilder to String.

Case 1: From StringBuffer to StringBuilder or vice-versa

It cannot be converted directly. The StringBuffer/StringBuilder object is first converted to a String using the toString() function, and then the String is converted back to a StringBuilder/StringBuffer object using constructors.

Case 2: From String to StringBuffer and StringBuilder 

This is an easy solution because the StringBuffer and StringBuilder class constructors can directly accept a String class object. Since the String class in Java is immutable, we can edit strings by converting them to StringBuilder or StringBuffer class objects.

Case 3: From StringBuffer and StringBuilder to String 

The toString() method, which is overridden in the StringBuilder and StringBuffer classes, can be used to convert data. 

String vs StringBuffer vs StringBuilder

These are some main difference between Java stringbuilder vs stringbuffer vs string.

  • StringBuffer and StringBuilder are mutable classes, but String is immutable.
  • StringBuilder is not synchronised or thread-safe, whereas StringBuffer is. StringBuilder is quicker than StringBuffer because of this.
  • The StringBuffer or StringBuilder class is used internally by the string concatenation operator (+).
  • Use StringBuilder instead of the StringBuffer class when manipulating strings in a single-threaded environment.

Performance Analysis

To check the performance of StringBuilder and StringBuffer, let us see an example with code:

public class Conc_Test{  
    public static void main(String[] args){  
  sTime = System.currentTimeMillis();  
        StringBuilder sb1 = new StringBuilder(“Lorem”);  
        for (int j=0; j<9999; j++){  
            sb1.append(“Ipsum”);  
        }  
        System.out.println(“StringBuilder Time: ” + (System.currentTimeMillis() – sTime)); 
        long sTime = System.currentTimeMillis();  
        StringBuffer sb2 = new StringBuffer(“Lorem”);  
        for (int j=0; j<9999; j++){  
            sb2.append(“Ipsum”);  
        }  
        System.out.println(“StringBuffer Time: ” + (System.currentTimeMillis() – sTime));  
           }  
}  

Output:

StringBuilder Time: 0ms

StringBuffer Time: 15ms

As we can acknowledge from the code above, StringBuilder performs better than StringBuffer in speed. Additionally, the memory consumption of the two differs, with StringBuffer using more memory than StringBuilder.

Wrapping up

Even though StringBuilder is classified as an alternative to the string class like StringBuffer, but it is a lot more flexible when it comes to usage.

So, As you can see that if you want to modify strings which by default are an immutable set of characters, you have to use StringBuffer or StringBuilder classes as they provide the ability to change strings. Both the classes are similar on the surface, as you can see, they use the same methods and similar constructors.

The difference between the two comes down to the synchronization and threading. If you are working in an environment where you don’t care about thread-safety, you can use StringBuilder as it will be a lot faster and efficient, but if you need thread safety, you should use StringBuffer as it is synchronized and thread-safe.

If you’re interested to learn more about Java, full-stack software development, check out upGrad & IIIT-B’s Executive PG Programme in Software Development – Specialisation in Cyber Security which is designed for working professionals and offers 500+ hours of rigorous training, 9+ projects, and assignments, IIIT-B Alumni status, practical hands-on capstone projects & job assistance with top firms.

Frequently Asked Questions (FAQs)

1. What are the different ways to create a mutable string?

Mutable strings are strings that can be modified and changed as and when required. StringBuilder and StringBuilder both can be used to create mutable strings. The append() method concatenates an argument with a string. The replace() method excuses a specified string from the beginIndex and endIndex. The capacity() method belongs to both StringBuffer and StringBuilder classes and is responsible for returning the capacity of the buffer. Every buffer has a dedicated default capacity set to 16. If the capacity increases by any margin, the entire capacity of the buffer increases by adding 2 to its old capacity doubled. So, if the default capacity is 16, the result will be 34.

2. What are the delete(), insert(), reverse(), and ensureCapacity methods of StringBuilder?

StringBuilder class is used to create mutable strings. There are many different methods of StringBuilder class. The StringBuilder delete() method will delete the string from the specified indexes, i.e., beginIndex and endIndex. The insert() method in the StringBuilder class is used to insert a string at a specified position. The reverse() method, as the name says, is a method in the StringBuilder class that reverses the current string. The ensureCapacity() method of the StringBuilder() class makes sure that the capacity specified is minimum to the current capacity. If the capacity exceeds, it then increases the capacity by following (oldcapacity*2)+2.

3. What are some of the methods of the String class?

There are many important methods of String class. The startWith() method ensures that the arguments passed and the beginning of the string are the same. EndsWith() ensures that the string should end with the same values as passed in the argument. The charAt() method will return a character residing at a specified index. The length() method will return the length of any string. The valueOf() method converts any form to a string, for example, int, long, float, and char to string. The replace() method of the String class replaces the first characters with the secondary characters in an array or any sequence.

RELATED PROGRAMS