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
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: Master 15 Powerful Methods of the StringBuffer Class

Updated on 20 January, 2025

6.58K+ views
20 min read

Ever been frustrated by how inefficient Java strings can be when you need frequent updates? If modifying strings feels like a memory-hogging nightmare, you’re not alone. Working with immutable strings often means creating new objects for every tiny change, draining performance and memory.

This is where the String Buffer in Java becomes your ultimate problem-solver. Unlike regular strings, the String Buffer class in Java allows for dynamic, efficient, and thread-safe string manipulation.

In this guide, you’ll discover how String Buffer in Java works, explore its key methods, and learn practical ways to implement it in your projects. By the end, you’ll be equipped to make smarter choices for handling strings, boosting your Java application’s performance. Ready to optimize your strings? Let’s dive in!

String Buffer in Java: What It Is and Why It Matters

Think of StringBuffer in Java as your go-to tool for managing strings that need frequent changes. Unlike String (which creates a new object every time it’s modified), String Buffer in Java lets you edit the same string efficiently. It’s part of the java.lang package, meaning it’s built right into Java, and it’s thread-safe, making it reliable for multi-threaded programs.

Here are some key characteristics:

  • Mutability: You can directly modify the content without creating new objects.
  • Thread Safety: It’s synchronised, so you don’t have to worry about conflicts when multiple threads are working on the same string.

Also Read: Java Tutorial: Learn Java Programming From Scratch For Beginners

Why Choose the String Buffer Class in Java?

If you’re working on a Java program where strings need frequent updates or multiple threads are involved, String Buffer class in Java is a game-changer. It combines efficiency, thread safety, and memory optimization, making it an ideal choice for handling dynamic strings in demanding applications. 

Here’s when you’ll love using String Buffer in Java:

  • Frequent Updates: If you’re adding, deleting, or replacing characters often, String Buffer saves you the hassle of creating new objects.
  • Multithreaded Programs: It ensures your data stays safe even when multiple threads try to update the string simultaneously.
  • Memory Efficiency: Unlike String, it reuses the same object, saving memory and boosting performance.

Using String Buffer in Java makes your programs faster and less resource-hungry when handling dynamic strings.

If you’re interested in learning more about String functions in Java and diving deeper into the language and its real-world applications, then sign up for upGrad’s software development courses. Upskill now and augment your career in programming!

Also Read: String Functions In Java | Java String [With Examples]

Visualizing the String Buffer Class in Java

Imagine a single block of memory that stretches or shrinks to fit your changes instead of creating a new block every time. That’s what String Buffer in Java does—it keeps everything dynamic and efficient.

Check out the diagram to see how it handles operations like append, insert, and delete while staying thread-safe.

 

Want to dive deeper into the aspects of Java and enhance your programming knowledge? Check out this free upGrad course on Java basics!

 

Also Read: Top 13 String Functions in Java | Java String [With Examples] 

Now that you know what String Buffer in Java is, let’s explore its most important methods. These 15 methods will show you how to handle dynamic strings effectively in Java.

15 Must-Know Methods of the String Buffer Class in Java

The String Buffer class in Java provides powerful methods to handle dynamic strings. Here’s a detailed explanation of 15 essential methods, with comments and outputs to help beginners understand.

Explore each of them in more detail below:

1. append(String str)

Adds the specified string to the end of the existing sequence. This method modifies the original String Buffer in Java without creating a new object, making it efficient for frequent string concatenations.

Sample Code:

// Create a new StringBuffer object with initial content "Hello"
StringBuffer sb = new StringBuffer("Hello"); 
// Append " World" to the existing content
sb.append(" World"); 
// Print the updated content
System.out.println(sb);

Output:

Hello World

Explanation: Adds the specified string to the end of the existing sequence. For example, appending " World" to "Hello" results in "Hello World". This method is efficient because it modifies the existing object instead of creating a new one, saving memory and processing time.

Also Read: Append in Java: A Complete Guide to Append Functions and Methods

2. insert(int offset, String str)

Inserts the specified string at the given position in the sequence. It shifts the existing characters to accommodate the new string without overwriting them.

Sample Code:

// Create a new StringBuffer object with initial content "Hello"
StringBuffer sb = new StringBuffer("Hello"); 
// Insert " Java" at index 5 (after "Hello")
sb.insert(5, " Java"); 
// Print the updated content
System.out.println(sb);

Output:

Hello Java

Explanation: Inserts the specified string at the given position within the sequence. For instance, inserting " Java" at position 5 in "Hello" produces "Hello Java". It adjusts the existing characters to accommodate the new content without overwriting them.

3. replace(int start, int end, String str)

Replace in Java replaces characters within the specified range with the given string. This allows you to modify a portion of the string directly without creating a new object.

Sample Code:

// Create a new StringBuffer object with initial content "Hello World"
StringBuffer sb = new StringBuffer("Hello World"); 
// Replace characters from index 6 to 10 ("World") with "Java"
sb.replace(6, 11, "Java"); 
// Print the updated content
System.out.println(sb);

Output:

Hello Java

Explanation: Replaces characters within the specified range with the provided string. For example, replacing the range 6-11 in "Hello World" with "Java" changes the string to "Hello Java". This is particularly useful for modifying specific portions of a string.

Also Read: String Replace in Python | Python String Replace

4. delete(int start, int end)

Removes characters within the specified range of the sequence. This operation is useful for trimming or removing unwanted sections from the string.

Sample Code:

// Create a new StringBuffer object with initial content "Hello World"
StringBuffer sb = new StringBuffer("Hello World"); 
// Delete characters from index 5 to 10 (" World")
sb.delete(5, 11); 
// Print the updated content
System.out.println(sb);

Output:

Hello

Explanation: Removes characters between the specified indices in the sequence. For instance, deleting characters from 5-11 in "Hello World" results in "Hello". This method is ideal for trimming unwanted parts from a string.

5. deleteCharAt(int index)

Deletes the character at the specified index in the sequence. It adjusts the remaining characters to fill the gap, keeping the sequence consistent.

Sample Code:

// Create a new StringBuffer object with initial content "Hello"
StringBuffer sb = new StringBuffer("Hello"); 
// Delete the character at index 0 ('H')
sb.deleteCharAt(0); 
// Print the updated content
System.out.println(sb);

Output:

ello

Explanation: Deletes a single character at the specified index in the sequence. For example, removing the character at index 0 in "Hello" results in "ello". The method shifts the remaining characters to close the gap, maintaining sequence integrity.

6. reverse()

Reverses the order of characters in the sequence. Reversing a string is particularly useful for tasks like reversing palindromes or manipulating text formats.

Sample Code:

// Create a new StringBuffer object with initial content "Hello"
StringBuffer sb = new StringBuffer("Hello"); 
// Reverse the characters in the buffer
sb.reverse(); 
// Print the reversed content
System.out.println(sb);

Output:

olleH

Explanation: Reverses the order of characters in the sequence. For example, reversing "Hello" produces "olleH". This method is useful for tasks such as reversing text, creating palindromes, or altering the format of strings.

7. capacity()

Returns the current capacity of the buffer, which is the total space allocated for the sequence. It includes extra space reserved for potential expansions, beyond the current string length.

Sample Code:

// Create a new StringBuffer object with initial content "Hello"
StringBuffer sb = new StringBuffer("Hello"); 
// Print the current capacity of the buffer
System.out.println(sb.capacity());

Output:

21

Explanation: Returns the current capacity of the buffer, which is the total allocated storage. For instance, a String Buffer in Java with initial content "Hello" may have a capacity of 21 (16 default + 5 for the string). This indicates how much the buffer can expand without resizing.

8. length()

Length in Java returns the number of characters currently in the buffer. This helps you determine the size of the sequence in use at any point.

Sample Code:

// Create a new StringBuffer object with initial content "Hello"
StringBuffer sb = new StringBuffer("Hello"); 
// Print the length of the current string
System.out.println(sb.length());

Output:

5

Explanation: Returns the number of characters currently stored in the buffer. For example, the length of "Hello" is 5. This method helps you understand how much of the buffer is actively being used.

9. charAt(int index)

charAt retrieves the character at the specified index in the sequence. This allows you to access specific elements of the string directly.

Sample Code:

// Create a new StringBuffer object with initial content "Hello"
StringBuffer sb = new StringBuffer("Hello"); 
// Get and print the character at index 1
System.out.println(sb.charAt(1));

Output:

e

Explanation: Retrieves the character at the specified index in the sequence. For example, calling charAt(1) on "Hello" returns 'e'. This is helpful for accessing specific characters for validation or manipulation.

10. setCharAt(int index, char ch)

Replaces the character at the specified index with the given character. This lets you update specific elements of the string efficiently.

Sample Code:

// Create a new StringBuffer object with initial content "Hello"
StringBuffer sb = new StringBuffer("Hello"); 
// Set the character at index 1 to 'a'
sb.setCharAt(1, 'a'); 
// Print the updated content
System.out.println(sb);

Output:

Hallo

Explanation: Replaces the character at the specified index with the provided character. For example, changing the character at index 1 in "Hello" to 'a' results in "Hallo". This method allows for quick and direct updates to specific characters.

11. substring(int start) / substring(int start, int end)

substring in Java extracts a portion of the sequence based on the specified indices. This is useful for isolating specific parts of the string for further operations.

Sample Code:

// Create a new StringBuffer object with initial content "Hello World"
StringBuffer sb = new StringBuffer("Hello World"); 
// Extract substring from index 6 to the end
System.out.println(sb.substring(6)); 
// Extract substring from index 0 to 4
System.out.println(sb.substring(0, 5));

Output:

World
Hello

Explanation: Extracts a portion of the sequence based on the specified indices. For instance, calling substring(6) on "Hello World" returns "World", while substring(0, 5) returns "Hello". This is useful for isolating parts of a string for further processing.

Also Read: String Buffer In Java: 11 Popular Methods Every Java Developer Should Know

12. ensureCapacity(int minimumCapacity)

Ensures that the buffer has at least the specified capacity, expanding it if necessary. This is useful for avoiding frequent reallocations when adding large amounts of data.

Sample Code:

// Create a new StringBuffer object with default capacity
StringBuffer sb = new StringBuffer(); 
// Ensure the buffer has a minimum capacity of 50
sb.ensureCapacity(50); 
// Print the new capacity
System.out.println(sb.capacity());

Output:

50

Explanation: Ensures that the buffer has at least the specified capacity, expanding it if needed. For example, ensuring a capacity of 50 guarantees sufficient space for future additions. This avoids frequent reallocations during large data operations.

13. trimToSize()

Reduces the buffer capacity to match the current sequence length. This is helpful for optimising memory usage once the string is finalised.

Sample Code:

// Create a new StringBuffer object with initial content "Hello"
StringBuffer sb = new StringBuffer("Hello"); 
// Trim the capacity to the length of the string
sb.trimToSize(); 
// Print the reduced capacity
System.out.println(sb.capacity());

Output:

5

Explanation: Reduces the buffer's capacity to match its current content length. For instance, if the buffer contains "Hello" with a capacity of 21, trimming reduces the capacity to 5. This is useful for optimising memory usage once the string is finalised.

14. indexOf(String str) / lastIndexOf(String str)

Finds the first or last occurrence of the specified substring within the sequence. These methods help locate and verify the presence of specific content.

Sample Code:

// Create a new StringBuffer object with initial content "Hello World"
StringBuffer sb = new StringBuffer("Hello World"); 
// Find the first occurrence of "World"
System.out.println(sb.indexOf("World")); 
// Find the last occurrence of 'o'
System.out.println(sb.lastIndexOf("o"));

Output:

6
7

Explanation: Finds the first or last occurrence of a substring within the sequence. For example, in "Hello World", indexOf("World") returns 6, and lastIndexOf("o") returns 7. These methods are ideal for locating specific content in a string.

15. toString()

toString () converts the content of the String Buffer in Java into a standard String. This allows you to use the sequence with methods and operations that require the String type.

Sample Code:

// Create a new StringBuffer object with initial content "Hello"
StringBuffer sb = new StringBuffer("Hello"); 
// Convert the content to a String object
String str = sb.toString(); 
// Print the String content
System.out.println(str);

Output:

Hello

Explanation: Converts the content of the String Buffer into a standard String. For example, calling toString() on a buffer containing "Hello" produces a String object "Hello". This is essential for integrating String Buffer with APIs and methods that require String objects.

Also Read: Top 7 Popular String Functions in C [With Examples]

The String Buffer class is a versatile and efficient solution for dynamic string manipulation in Java. By mastering its key methods, you can optimize performance and handle complex string operations with ease.

Key Constructors of the String Buffer Class in Java

The String Buffer class provides three key constructors to initialise objects based on your specific requirements. Each constructor serves a unique purpose, from creating an empty buffer to starting with predefined content. 

Let’s explore these in detail:

1. StringBuffer()

This constructor creates an empty String Buffer object with a default capacity of 16 characters. The buffer dynamically grows as more characters are added.

Code Example:

// Create an empty StringBuffer with default capacity
StringBuffer sb = new StringBuffer();
System.out.println("Capacity: " + sb.capacity());

Output:

Capacity: 16

Explanation: The default capacity allows you to start with an empty buffer and add content without immediate memory resizing. The capacity expands automatically when it exceeds 16.

2. StringBuffer(int capacity)

This constructor creates an empty String Buffer with a specified capacity. It’s ideal when you know the approximate size of the data you’ll handle, avoiding unnecessary memory reallocation.

Code Example:

// Create a StringBuffer with a custom capacity of 50
StringBuffer sb = new StringBuffer(50);
System.out.println("Capacity: " + sb.capacity());

Output:

Capacity: 50

Explanation: By predefining the capacity, you minimise the overhead of resizing the buffer as you add content. This is especially useful for large datasets or frequent modifications.

3. StringBuffer(String str)

This constructor initialises a String Buffer with the specified string and sets the capacity to 16 plus the string's length.

Code Example:

// Create a StringBuffer with initial content "Hello"
StringBuffer sb = new StringBuffer("Hello");
System.out.println("Content: " + sb);
System.out.println("Capacity: " + sb.capacity());

Output:

Content: Hello
Capacity: 21

Explanation: This constructor is useful when starting with predefined content, such as "Hello". The initial capacity includes additional space (16 characters) for appending or modifying the content dynamically.

After mastering its methods, understanding how to create and initialise String Buffer objects is essential. Here’s a guide to the key constructors and their use cases.

Essential Methods of String Buffer in Java

The String Buffer class offers versatile methods for efficient string manipulation. Let’s look at the most commonly used ones, their functionality, and how they simplify tasks:

1. append(String str)

Adds the specified string to the end of the sequence. This method is efficient for concatenation since it modifies the same buffer.

Code Example:

StringBuffer sb = new StringBuffer("Hello");
sb.append(" World");
System.out.println(sb);

Output:

Hello World

Explanation: The append method adds " World" to the existing content "Hello". Unlike String, this operation doesn’t create a new object, making it memory-efficient.

2. insert(int offset, String str)

Inserts the specified string at the given position within the sequence. It shifts existing characters to accommodate the new content.

Code Example:

StringBuffer sb = new StringBuffer("Hello");
sb.insert(5, " Java");
System.out.println(sb);

Output:

Hello Java

Explanation: The string " Java" is inserted at position 5, right after "Hello". This operation ensures no data is overwritten, only rearranged.

3. replace(int start, int end, String str)

Replaces characters in the specified range with the given string. It’s useful for updating specific sections of a string.

Code Example:

StringBuffer sb = new StringBuffer("Hello World");
sb.replace(6, 11, "Java");
System.out.println(sb);

Output:

Hello Java

Explanation: Characters from index 6 to 10 ("World") are replaced by "Java". The method provides an efficient way to update parts of the sequence without creating a new string.

4. delete(int start, int end)

Removes characters between the specified indices, shrinking the sequence accordingly.

Code Example:

StringBuffer sb = new StringBuffer("Hello World");
sb.delete(5, 11);
System.out.println(sb);

Output:

Hello

Explanation: The delete method removes characters from index 5 to 10 (" World"). It’s useful for trimming unwanted parts of the sequence.

5. reverse()

Reverses the sequence of characters in the buffer. This is particularly helpful for reversing words, palindromes, or other text transformations.

Code Example:

StringBuffer sb = new StringBuffer("Hello");
sb.reverse();
System.out.println(sb);

Output:

olleH

Explanation: The reverse method rearranges the characters in the sequence, producing the reversed string "olleH" from "Hello".

These constructors and methods showcase the flexibility and power of the String Buffer class. It’s designed for efficient, thread-safe string manipulation, making it an invaluable tool for Java developers. 

Also Read: 45+ Best Java Project Ideas for Beginners in 2025 with Source Code & Best Practices

Choosing the right tool for string handling depends on your application’s needs. Let’s compare String Buffer, String Builder, and String to help you make the best choice.

upGrad’s Exclusive Software Development Webinar for you –

SAAS Business – What is So Different?

 

String Buffer vs. String Builder vs. String: What to Use and When

Choosing the right class—String Buffer, String Builder, or String—depends on the specific requirements of your application.

String Buffer Class in Java vs. String Builder

Both String Buffer and String Builder are mutable classes designed for efficient string manipulation, but their key differences lie in thread safety and performance.

Here’s a comparison table:

Feature

String Buffer

String Builder

Thread-Safety Synchronized and thread-safe. Ideal for multi-threaded environments. Not thread-safe. Suited for single-threaded applications.
Performance Slightly slower due to synchronization overhead. Faster as it doesn’t require thread synchronization.
Use Case Use in multi-threaded applications requiring string modifications. Use in single-threaded environments for optimal performance.

Key Points:

  • Thread-Safety: If multiple threads are accessing and modifying the same string, use String Buffer. Its synchronized methods ensure data integrity.
  • Performance: For single-threaded applications, String Builder is faster because it avoids synchronization overhead.

String Buffer in Java vs. String

String Buffer and String differ fundamentally in their mutability and memory efficiency.

Here’s a comparison table:

Feature

String Buffer

String

Mutability Mutable: Modifications happen in the same object. Immutable: Every modification creates a new object.
Efficiency Efficient for repeated modifications like appending, inserting, or deleting. Inefficient for frequent modifications due to object creation overhead.
Thread-Safety Thread-safe. Suitable for multi-threaded applications. Not thread-safe. Needs external synchronization in multi-threaded contexts.
Use Case Use for dynamic strings with frequent modifications. Use for static strings or when immutability is required.

Key Points:

  • Mutability: Unlike String, String Buffer avoids creating new objects for every modification, making it memory efficient.
  • Efficiency: For operations like appending or replacing text multiple times, String Buffer is significantly faster.

Consider the following when choosing the string for your project:

1. Use String:

  • For static strings that don’t require frequent modifications.
  • In scenarios where immutability is essential for security or data consistency (e.g., string keys in hash maps).

2. Use String Builder:

  • In single-threaded environments where performance is critical.
  • For tasks like building strings in loops or performing multiple concatenations.

3. Use String Buffer:

  • In multi-threaded applications where string modifications need to be synchronized.
  • For thread-safe operations like logging or shared data string manipulations.

By understanding these differences, you can select the most suitable class for your application, optimising both performance and resource usage.

Also Read: String Buffer vs. String Builder: Difference Between String Buffer & String Builder

Once you’re familiar with the basics, it’s time to explore advanced techniques. These approaches will help you optimize String Buffer for high-performance applications.

Advanced Techniques for Mastering String Buffer in Java

The String Buffer class in Java offers more than basic string manipulation. By leveraging its advanced features, you can optimize performance and handle complex scenarios effectively. 

Optimizing String Buffer in Java for High-Performance Applications

String concatenation using String creates new objects every time, which impacts memory and performance. String Buffer eliminates this issue by modifying strings in place.

Example: Performance Comparison

// Using String (inefficient due to immutability)
String str = "";
for (int i = 0; i < 1000; i++) {
    str += i;
}

// Using StringBuffer (efficient due to mutability)
StringBuffer sb = new StringBuffer();
for (int i = 0; i < 1000; i++) {
    sb.append(i);
}
System.out.println(sb.toString());

Explanation: The String approach creates 1000 intermediate objects, while String Buffer efficiently updates the same object, reducing memory overhead and improving speed.

Managing Capacity in String Buffer Class in Java

Efficient memory management is critical in high-performance applications. The capacity() and ensureCapacity() methods help optimize resource usage.

Example: Using capacity() and ensureCapacity()

// Create a StringBuffer with default capacity
StringBuffer sb = new StringBuffer();
System.out.println("Initial Capacity: " + sb.capacity()); // Output: 16

// Add content and check capacity
sb.append("Hello, World!");
System.out.println("Capacity after appending: " + sb.capacity()); // Output: 16

// Ensure a larger capacity
sb.ensureCapacity(50);
System.out.println("Capacity after ensuring: " + sb.capacity()); // Output: 50

Explanation: The default capacity of 16 grows dynamically when exceeded. Using ensureCapacity() prevents frequent reallocations when handling large strings, improving performance.

Practical Applications of the String Buffer Class in Java

The versatility of String Buffer makes it ideal for a variety of real-world scenarios. Here are some examples:

1. Dynamic Query Generation

Code Example:

StringBuffer query = new StringBuffer("SELECT * FROM users WHERE");
query.append(" age > 18");
query.append(" AND city = 'New York'");
System.out.println(query);

Output:

SELECT * FROM users WHERE age > 18 AND city = 'New York'

Explanation: String Buffer simplifies building SQL queries dynamically by appending conditions based on user input.

2. User Input Handling

Code Example:

StringBuffer userInput = new StringBuffer("User:");
userInput.append(" John");
userInput.append(" Doe");
System.out.println(userInput);

Output:

User: John Doe

Explanation: When handling inputs that need to be concatenated or formatted, String Buffer ensures efficient and safe modifications.

3. File Processing

Code Example:

StringBuffer fileContent = new StringBuffer();
fileContent.append("Line 1\n");
fileContent.append("Line 2\n");
fileContent.append("Line 3\n");
System.out.println(fileContent);

Output:

Line 1
Line 2
Line 3

Explanation: When processing files line by line, String Buffer efficiently manages the content before writing it back to a file.

By mastering these advanced techniques, you can use String Buffer to optimize your applications, manage resources effectively, and handle complex string operations with ease. 

Also Read: Top 130+ Java Interview Questions & Answers

Even with advanced techniques, knowing how to avoid pitfalls and follow best practices ensures you use String Buffer efficiently and effectively in your projects.

Best Practices for Using String Buffer in Java Effectively

To maximize the efficiency of String Buffer, it’s essential to understand its strengths and limitations. These best practices help you avoid common pitfalls and leverage the class effectively in your Java applications.

Common Pitfalls with String Buffer Class in Java

While String Buffer is powerful, improper use can lead to inefficiencies. Here are common issues and how to avoid them:

1. Inefficient Capacity Management: Relying solely on default capacity can cause frequent reallocations as the buffer grows. Use ensureCapacity() to pre-allocate enough space when working with large data.

2. Unnecessary Conversions: Avoid converting between String and String Buffer repeatedly, as it adds unnecessary processing overhead. Use one class consistently unless absolutely needed.

3. Overuse in Single-Threaded Environments: Using String Buffer in single-threaded applications adds unneeded overhead due to its synchronisation. Opt for String Builder in these cases for better performance.

Expert Tips for Using String Buffer in Java

Whether you're working on multi-threaded applications or handling large-scale string modifications, these best practices will help you optimize performance and ensure efficient use of resources.

Here are actionable tips to get the most out of String Buffer: 

1. Leverage String Buffer in Multi-Threaded Applications: String Buffer is thread-safe, making it the preferred choice for shared data in multi-threaded scenarios. Its synchronisation ensures data consistency across threads.

2. Use ensureCapacity() to Avoid Performance Bottlenecks: Predefine the capacity when you know the approximate size of data. For example, allocate a capacity of 100 when appending large strings to prevent frequent memory reallocations.

Code Example:

StringBuffer sb = new StringBuffer();
sb.ensureCapacity(100); // Pre-allocate memory
sb.append("Large data to be added...");

3. Prefer String Buffer Over String for Repeated Modifications: When performing operations like appending, inserting, or replacing multiple times, String Buffer outperforms String due to its mutability.

Code Example:

StringBuffer sb = new StringBuffer("Initial");
sb.append(" Data");
sb.insert(7, " Dynamic");
System.out.println(sb); // Output: Initial Dynamic Data

4. Combine with Other Optimisations for Better Results: Use String Buffer with efficient algorithms and data structures for tasks like dynamic query generation, large-scale data formatting, or file processing.

By following these practices, you can optimize your use of String Buffer for high performance, reduced memory usage, and better application reliability.

Also Read: Top 8 Reasons Why Java Is So Popular and Widely Used in 2025

To truly excel, learning from experts and applying your skills to real-world projects is key. upGrad’s programs can help you master String Buffer and elevate your Java skills.

How upGrad Can Help You Master the String Buffer Class in Java?

Mastering the String Buffer class in Java and other Java essentials is critical for becoming a proficient developer. upGrad’s comprehensive Java programming courses are designed to equip you with the skills needed for success in real-world software development.

upGrad offers hands-on programming training with real-world projects, expert mentorship, and 100+ free courses. Join over 1 million learners to build job-ready skills and tackle industry challenges.

Here are some relevant courses you can check out:

Course Title

Description

Best Full Stack Developer Bootcamp 2024 A program designed to equip learners with essential skills in both front-end and back-end development, preparing them for successful careers in software engineering.
Java Object-oriented Programming Master the fundamentals of Object-Oriented Programming (OOP) in Java with this free course, and learn key concepts like classes, inheritance, and polymorphism.
JavaScript Basics from Scratch This free course offers a comprehensive introduction to fundamental programming concepts and web development skills using JavaScript.
Master of Design in User Experience Earn a Master’s in User Experience Design from Jindal School of Art and Architecture, and gain expertise in creating intuitive, user-centered designs for digital products.

 

Also, get personalized career counseling with upGrad to shape your programming future, or you can visit your nearest upGrad center and start hands-on training today!

 

Boost your career with our popular Software Engineering courses, offering hands-on training and expert guidance to turn you into a skilled software developer.

Master in-demand Software Development skills like coding, system design, DevOps, and agile methodologies to excel in today’s competitive tech industry.

Stay informed with our widely-read Software Development articles, covering everything from coding techniques to the latest advancements in software engineering.

Frequently Asked Questions

1. Can I specify a custom capacity for a String Buffer object?

Yes, you can use the StringBuffer(int capacity) constructor to set an initial capacity. This helps avoid frequent memory reallocations when handling large strings.wsx

2. What happens if I exceed the capacity of a String Buffer?

The buffer automatically expands by reallocating memory, typically doubling the existing capacity. This ensures you can keep adding characters without errors.

3. Is String Buffer compatible with legacy Java code?

Yes, String Buffer has been part of Java since version 1.0. It integrates seamlessly with older Java applications that require thread-safe string operations.

4. Can I convert a String Buffer to a String Builder or vice versa?

You can convert between String Buffer and String Builder by first using the toString() method and then passing the result to the desired class's constructor. However, note that this involves creating a new object.

5. What’s the default capacity of a newly created String Buffer?

The default capacity of a String Buffer is 16 characters. This excludes any initial content you specify.

6. Does String Buffer support Unicode characters?

Yes, String Buffer fully supports Unicode. You can use it to handle strings in any language or encoding.

7. Are methods like substring() thread-safe in String Buffer?

While the String Buffer class itself is thread-safe, methods like substring() return a String, which isn’t thread-safe unless handled externally.

8. How is String Buffer different from String BufferInputStream?

String Buffer is for dynamic string manipulation, while String BufferInputStream is a legacy class used to read strings as input streams. The latter is now deprecated in favor of modern alternatives like StringReader.

9. Can I reduce the capacity of a String Buffer to save memory?

Yes, you can use the trimToSize() method to shrink the buffer's capacity to its current length. This is useful when you no longer expect the buffer to grow.

10. Does String Buffer have any thread-safety limitations?

While String Buffer is thread-safe, performance may degrade due to synchronisation overhead in high-concurrency scenarios. For better scalability, consider String Builder with explicit synchronisation.

11. Is String Buffer suitable for formatting large texts like reports?

String Buffer is well-suited for tasks like report generation or dynamic content assembly. Its mutability makes it efficient for appending and modifying large texts.

RELATED PROGRAMS