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 In Java: 11 Popular Methods Every Java Developer Should Know

Updated on 18 November, 2022

6.49K+ views
9 min read

Introduction to StringBuffer in Java

StringBuffer in java is a class that inherits methods from java.lang.Object class. It is a peer class of String that is used to create modifiable or mutable String. It provides much of String’s functionality except that it can be changed, i.e., it represents writable and growable character sequences instead of immutable and fixed-length character sequences. Here are some essential points about the java.lang.StringBuffer in Java:

·  The content and length of the sequence of characters can be changed through various method calls.

·  It is thread-safe, i.e., safe for use by multiple threads

·   Every StringBuffer in java has a capacity.

·  The substrings and characters can be appended in the end or inserted in the middle. It automatically grows and makes room for additions. Often, more characters are preallocated than needed to allow room for growth.

Here is how the StringBuffer in the Java class is declared:

public final class StringBuffer

extends Object

implements Serializable, CharSequence

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

Constructors of StringBuffer Class

1. StringBuffer() – This is used to construct a string buffer with an initial capacity of 16 characters and no characters in it. Syntax:

StringBuffer a =new StringBuffer();

2. StringBuffer (CharSequence seq) – This is used to construct a string buffer that contains the same characters as in the CharSequence.

Check out upGrad’s Advanced Certification in Cyber Security 

3. StringBuffer (int capacity) – This is used to create a string buffer whose initial capacity is specified and with no characters. Syntax:

StringBuffer a=new StringBuffer(10);

4. StringBuffer (String str) – This is used to create a string buffer with the given String content. Syntax:

StringBuffer a=new StringBuffer(“stringbuffer in java”);

Check out upGrad’s Full Stack Development Bootcamp (JS/MERN)

Read: Difference Between String Buffers and String Builders

11 Popular Methods

1) StringBuffer in Java Append() Method

.append() is used to concatenate the given string and argument. Here’s an example:

import java.io.*;

public class buffer {

       public static void main(String[] args)

       {

                        StringBuffer a = new StringBuffer(“stringbuffer”);

                        a.append(“in Java”);

                        System.out.println(a);

                        a.append(0);

                        System.out.println(a);

       }

}

Output: 

2) StringBuffer in Java Insert() Method

.insert() method is used to insert a given string with the main string at the specified position. Here’s an example:

import java.io.*;
public class buffer {
       public static void main(String[] args)
       {
                        StringBuffer a = new StringBuffer(“stringbuffer”);
                        a.insert(5, “for”);
                        System.out.println(a);
                        a.insert(0, 5);
                        System.out.println(a);
                        a.insert(3, false);
                        System.out.println(a);
                        a.insert(5, 41.55d);
                        System.out.println(a);
                        a.insert(8, 41.55f);
                        System.out.println(a);
                        char arr[] = { ‘j’, ‘a’, ‘v’, ‘a’ };
                        a.insert(2, arr);
                        System.out.println(a);
       } }

Output:

Also Read: Java Project Ideas &  Topics

upGrad’s Exclusive Software Development Webinar for you –

SAAS Business – What is So Different?

3) StringBuffer in java replace() method

.replace() is used to replace a part of string as specified in the range (beginIndex, endIndex). Here’s an example:

import java.io.*;

public class buffer {

           public static void main(String[] args)

           {

                          StringBuffer a = new StringBuffer(“stringbuffer”);

                          a.replace(5, 8, “are”);

                          System.out.println(a); 

              }

}

Output:

4) StringBuffer in Java Delete() Method

.delete() is used to delete the string as specified in the range (beginIndex, endIndex).

.deleteCharAt() is used to delete the character at a specific index. This method returns the resulting stringbuffer object. Here’s an example:

import java.io.*;

public class buffer {

           public static void main(String[] args)

           {

                          StringBuffer a = new StringBuffer(“string buffer in java”);

                          a.delete(0, 6);

                          System.out.println(a);

                          a.deleteCharAt(7);

                          System.out.println(a);

           }

}

Output: 

5) StringBuffer in Java Reverse() Method

.reverse() as the name suggests is used to reverse the given string. Here’s an example:

import java.io.*;

public class buffer {

           public static void main(String[] args)

           {

                          StringBuffer a = new StringBuffer(“stringbuffer”);

                          a.reverse();

                          System.out.println(a);

           }

}

Output:

6) StringBuffer in Java Capacity() Method

.capacity() of StringBuffer in java class is used to return the current capacity of the buffer. 16 is the default capacity. The capacity increases by increasing the number of characters. The new capacity = (old capacity*2)+2. i.e., if the current capacity is 16, the new capacity will be 32+2=34.

.length is used to find the length of a StringBuffer in java. For example:

import java.io.*;

public class buffer {

           public static void main(String[] args)

           {

                          StringBuffer a = new StringBuffer(“stringbuffer”);

                          int p = a.length();

                          int q = a.capacity();

                          System.out.println(“Length of string is=” + p);

                          System.out.println(“Capacity of string is=” + q);

           }

}

Output:

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

 

7) StringBuffer in Java ensureCapacity() Method

.ensureCapacity() of stringbuffer class is used to ensure that the specified capacity is the minimum to the current capacity. If the given capacity is greater than the current capacity, the new capacity becomes (oldcapacity*2)+2. i.e. the capacity becomes 34 if oldcapacity is 16. For example:

     public class buffer{ 

           public static void main(String args[]){ 

           StringBuffer a=new StringBuffer(); 

           System.out.println(a.capacity());

           a.append(“Hello”); 

           System.out.println(a.capacity());

           a.append(“java”); 

           System.out.println(a.capacity()); 

           a.ensureCapacity(10);

           System.out.println(a.capacity()); 

           a.ensureCapacity(50);

           System.out.println(a.capacity());

           } 

           }

Output:

8. charAt(int index) – This method is used to return the character at the given index.

9. substring( int begIndex) – This method is used to return a given string’s substring starting from the beginIndex.

10. substring(int beginIndex, int endIndex) – This method is used to return the given String’s substring starting at beginIndex and ending at endIndex.

11. void trimToSize() – This method is used to reduce storage space for the character sequence

Difference Between String and StringBuffer in Java

We use this example to create objects of the StringBuffer and String class and modify them. We see that the StringBuffer object gets modified, whereas String does not. See the example below:

public class buffer {

 public static void main(String args[])

 {

  String str = “string”;

  str.concat(“buffer”);

  System.out.println(str);

  StringBuffer strB = new StringBuffer(“string”);

  strB.append(“buffer”);

  System.out.println(strB);

 }

}

Explanation: The output is such because strings are immutable. If we try to concatenate the string object, it will not be altered. However, a StringBuffer in java creates mutable objects. Thus, it can be altered.

Interesting Points

  1. It extends the Object class.
  2. The implemented interfaces of StringBuffer in java are Appendable, Serializable, and CharSequence.
  3. The methods of StringBuffer can be synchronized wherever necessary. This means all operations behave as if they occur in some serial order.
  4. When an operation occurs involving the source sequence, this class synchronizes only on the string buffer operating and not the source.
  5. Some of the methods inherited from object class are equals, clone, getClass, notify, notifyAll, hashCode, and finalize.

Conclusion

StringBuffer in java creates modifiable string objects. Thus, we can use StringBuffer to append, replace, reverse, concatenate and modify the sequence of characters or strings. The methods under the StringBuffer class adhere to these functions. To sum up, StringBuffer in java is used only when multiple threads are modifying the contents of the StringBuffer. It is faster than String.

 In this article, we learned every detail about Java StringBuffer.If you are looking to learn more about java and move up in your technical career, explore courses by upGrad-India’s largest online higher education company.

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 Full Stack Development 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 exactly are Strings in Java?

Strings are Java objects that represent a sequence of characters. They can be created using either the String Literal or the NEW keyword. Strings in Java are immutable and are represented in UTF-16 format. When a new String is created, it searches the JVM string pool for a String with the same value. If it finds the same value, it returns the reference; otherwise, it creates a String object and adds it to the String pool. Aside from that, String uses the + operator to join two strings and internally uses the StringBuffer to do so.

2. What is the difference between StringBuffer and StringBuilder?

StringBuilder's function is very similar to that of the StringBuffer class in that both provide an alternative to String Class by creating a mutable sequence of characters. The StringBuilder class, on the other hand, differs from the StringBuffer class in terms of synchronization. The StringBuilder class does not provide synchronization guarantees, whereas the StringBuffer class does. As a result, this class is intended to be used as a drop-in replacement for StringBuffer in places where StringBuffer was previously used by a single thread (as is generally the case). It is recommended that this class be used instead of StringBuffer whenever possible because it is faster in most implementations. StringBuilder instances should not be used by multiple threads.

3. Why should you learn Java programming?

Java is an absolute must for students around the world who want to become great software engineers, especially if they work in the software development domain. Some of the primary benefits of learning Java programming include Object-Oriented applications. Because it is based on the Object model, Java can be extended. Java also is platform-independent, unlike many other programming languages, including C and C++. Moreover, it can be compiled into platform-independent bytecode rather than platform-specific machine code, which is distributed over the Internet for JVM interpretation.

RELATED PROGRAMS