StringBuffer and StringBuilder Class in Java

Last updated on Dec 29 2022
Prabhas Ramanathan

Java StringBuffer class is used to create mutable (modifiable) string. The StringBuffer class in java is same as String class except it is mutable i.e. it can be changed.
Note: Java StringBuffer class is thread-safe i.e. multiple threads cannot access it simultaneously. So it is safe and will result in an order.

Table of Contents

Important methods of StringBuffer class

Constructor Description
StringBuffer() creates an empty string buffer with the initial capacity of 16.
StringBuffer(String str) creates a string buffer with the specified string.
StringBuffer(int capacity) creates an empty string buffer with the specified capacity as length.

Important methods of StringBuffer class

Modifier and Type Method Description
public synchronized StringBuffer append(String s) is used to append the specified string with this string. The append() method is overloaded like append(char), append(boolean), append(int), append(float), append(double) etc.
public synchronized StringBuffer insert(int offset, String s) is used to insert the specified string with this string at the specified position. The insert() method is overloaded like insert(int, char), insert(int, boolean), insert(int, int), insert(int, float), insert(int, double) etc.
public synchronized StringBuffer replace(int startIndex, int endIndex, String str) is used to replace the string from specified startIndex and endIndex.
public synchronized StringBuffer delete(int startIndex, int endIndex) is used to delete the string from specified startIndex and endIndex.
public synchronized StringBuffer reverse() is used to reverse the string.
public int capacity() is used to return the current capacity.
public void ensureCapacity(int minimumCapacity) is used to ensure the capacity at least equal to the given minimum.
public char charAt(int index) is used to return the character at the specified position.
public int length() is used to return the length of the string i.e. total number of characters.
public String substring(int beginIndex) is used to return the substring from the specified beginIndex.
public String substring(int beginIndex, int endIndex) is used to return the substring from the specified beginIndex and endIndex.

What is mutable string

A string that can be modified or changed is known as mutable string. StringBuffer and StringBuilder classes are used for creating mutable string.

1) StringBufferappend() method

The append() method concatenates the given argument with this string.

1. class StringBufferExample{ 
2. public static void main(String args[]){ 
3. StringBuffer sb=new StringBuffer("Hello "); 
4. sb.append("Java");//now original string is changed 
5. System.out.println(sb);//prints Hello Java 
6. } 
7. } 
2) StringBufferinsert() method
The insert() method inserts the given string with this string at the given position.
1. class StringBufferExample2{ 
2. public static void main(String args[]){ 
3. StringBuffer sb=new StringBuffer("Hello "); 
4. sb.insert(1,"Java");//now original string is changed 
5. System.out.println(sb);//prints HJavaello 
6. } 
7. }

3) StringBufferreplace() method

The replace() method replaces the given string from the specified beginIndex and endIndex.

1. class StringBufferExample3{ 
2. public static void main(String args[]){ 
3. StringBuffer sb=new StringBuffer("Hello"); 
4. sb.replace(1,3,"Java"); 
5. System.out.println(sb);//prints HJavalo 
6. } 
7. }

4) StringBufferdelete() method

The delete() method of StringBuffer class deletes the string from the specified beginIndex to endIndex.

1. class StringBufferExample4{ 
2. public static void main(String args[]){ 
3. StringBuffer sb=new StringBuffer("Hello"); 
4. sb.delete(1,3); 
5. System.out.println(sb);//prints Hlo 
6. } 
7. }

5) StringBufferreverse() method

The reverse() method of StringBuilder class reverses the current string.

1. class StringBufferExample5{ 
2. public static void main(String args[]){ 
3. StringBuffer sb=new StringBuffer("Hello"); 
4. sb.reverse(); 
5. System.out.println(sb);//prints olleH 
6. } 
7. }

6) StringBuffercapacity() method

The capacity() method of StringBuffer class returns the current capacity of the buffer. The default capacity of the buffer is 16. If the number of character increases from its current capacity, it increases the capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be (16*2)+2=34.

1. class StringBufferExample6{ 
2. public static void main(String args[]){ 
3. StringBuffer sb=new StringBuffer(); 
4. System.out.println(sb.capacity());//default 16 
5. sb.append("Hello"); 
6. System.out.println(sb.capacity());//now 16 
7. sb.append("java is my favourite language"); 
8. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2 
9. } 
10. }

7) StringBufferensureCapacity() method

The ensureCapacity() method of StringBuffer class ensures that the given capacity is the minimum to the current capacity. If it is greater than the current capacity, it increases the capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be (16*2)+2=34.

1. class StringBufferExample7{ 
2. public static void main(String args[]){ 
3. StringBuffer sb=new StringBuffer(); 
4. System.out.println(sb.capacity());//default 16 
5. sb.append("Hello"); 
6. System.out.println(sb.capacity());//now 16 
7. sb.append("java is my favourite language"); 
8. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2 
9. sb.ensureCapacity(10);//now no change 
10. System.out.println(sb.capacity());//now 34 
11. sb.ensureCapacity(50);//now (34*2)+2 
12. System.out.println(sb.capacity());//now 70 
13. } 
14. }

Java StringBuilder class

Java StringBuilder class is used to create mutable (modifiable) string. The Java StringBuilder class is same as StringBuffer class except that it is non-synchronized. It is available since JDK 1.5.

Important Constructors of StringBuilder class

Constructor Description
StringBuilder() creates an empty string Builder with the initial capacity of 16.
StringBuilder(String str) creates a string Builder with the specified string.
StringBuilder(int length) creates an empty string Builder with the specified capacity as length.

Important methods of StringBuilder class

Method Description
public StringBuilder append(String s) is used to append the specified string with this string. The append() method is overloaded like append(char), append(boolean), append(int), append(float), append(double) etc.
public StringBuilder insert(int offset, String s) is used to insert the specified string with this string at the specified position. The insert() method is overloaded like insert(int, char), insert(int, boolean), insert(int, int), insert(int, float), insert(int, double) etc.
public StringBuilder replace(int startIndex, int endIndex, String str) is used to replace the string from specified startIndex and endIndex.
public StringBuilder delete(int startIndex, int endIndex) is used to delete the string from specified startIndex and endIndex.
public StringBuilder reverse() is used to reverse the string.
public int capacity() is used to return the current capacity.
public void ensureCapacity(int minimumCapacity) is used to ensure the capacity at least equal to the given minimum.
public char charAt(int index) is used to return the character at the specified position.
public int length() is used to return the length of the string i.e. total number of characters.
public String substring(int beginIndex) is used to return the substring from the specified beginIndex.
public String substring(int beginIndex, int endIndex) is used to return the substring from the specified beginIndex and endIndex.

Java StringBuilder Examples

Let’s see the examples of different methods of StringBuilder class.

1) StringBuilder append() method

The StringBuilder append() method concatenates the given argument with this string.

1. class StringBuilderExample{ 
2. public static void main(String args[]){ 
3. StringBuilder sb=new StringBuilder("Hello "); 
4. sb.append("Java");//now original string is changed 
5. System.out.println(sb);//prints Hello Java 
6. } 
7. }

2) StringBuilder insert() method

The StringBuilder insert() method inserts the given string with this string at the given position.

1. class StringBuilderExample2{ 
2. public static void main(String args[]){ 
3. StringBuilder sb=new StringBuilder("Hello "); 
4. sb.insert(1,"Java");//now original string is changed 
5. System.out.println(sb);//prints HJavaello 
6. } 
7. }

3) StringBuilder replace() method

The StringBuilder replace() method replaces the given string from the specified beginIndex and endIndex.

1. class StringBuilderExample3{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder(“Hello”);
4. sb.replace(1,3,”Java”);
5. System.out.println(sb);//prints HJavalo
6. }
7. }

4) StringBuilder delete() method

The delete() method of StringBuilder class deletes the string from the specified beginIndex to endIndex.

1. class StringBuilderExample4{ 
2. public static void main(String args[]){ 
3. StringBuilder sb=new StringBuilder("Hello"); 
4. sb.delete(1,3); 
5. System.out.println(sb);//prints Hlo 
6. } 
7. }

5) StringBuilder reverse() method

The reverse() method of StringBuilder class reverses the current string.

1. class StringBuilderExample5{ 
2. public static void main(String args[]){ 
3. StringBuilder sb=new StringBuilder("Hello"); 
4. sb.reverse(); 
5. System.out.println(sb);//prints olleH 
6. } 
7. }

6) StringBuilder capacity() method

The capacity() method of StringBuilder class returns the current capacity of the Builder. The default capacity of the Builder is 16. If the number of character increases from its current capacity, it increases the capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be (16*2)+2=34.

1. class StringBuilderExample6{ 
2. public static void main(String args[]){ 
3. StringBuilder sb=new StringBuilder(); 
4. System.out.println(sb.capacity());//default 16 
5. sb.append("Hello"); 
6. System.out.println(sb.capacity());//now 16 
7. sb.append("java is my favourite language"); 
8. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2 
9. } 
10. }

7) StringBuilder ensureCapacity() method

The ensureCapacity() method of StringBuilder class ensures that the given capacity is the minimum to the current capacity. If it is greater than the current capacity, it increases the capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be (16*2)+2=34.

1. class StringBuilderExample7{ 
2. public static void main(String args[]){ 
3. StringBuilder sb=new StringBuilder(); 
4. System.out.println(sb.capacity());//default 16 
5. sb.append("Hello"); 
6. System.out.println(sb.capacity());//now 16 
7. sb.append("java is my favourite language"); 
8. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2 
9. sb.ensureCapacity(10);//now no change 
10. System.out.println(sb.capacity());//now 34 
11. sb.ensureCapacity(50);//now (34*2)+2 
12. System.out.println(sb.capacity());//now 70 
13. } 
14. }

So, this brings us to the end of blog. This Tecklearn ‘StrinngBuffer and StringBuilder Class in Java’ blog helps you with commonly asked questions if you are looking out for a job in Java Programming. If you wish to learn Java and build a career Java Programming domain, then check out our interactive, Java and JEE Training, that comes with 24*7 support to guide you throughout your learning period. Please find the link for course details:

Java and JEE Training

Java and JEE Training

About the Course

Java and JEE Certification Training is designed by professionals as per the industrial requirements and demands. This training encompasses comprehensive knowledge on basic and advanced concepts of core Java & J2EE along with popular frameworks like Hibernate, Spring & SOA. In this course, you will gain expertise in concepts like Java Array, Java OOPs, Java Function, Java Loops, Java Collections, Java Thread, Java Servlet, and Web Services using industry use-cases and this will help you to become a certified Java expert.

Why Should you take Java and JEE Training?

• Java developers are in great demand in the job market. With average pay going between $90,000/- to $120,000/- depending on your experience and the employers.
• Used by more than 10 Million developers worldwide to develop applications for 15 Billion devices.
• Java is one of the most popular programming languages in the software world. Rated #1 in TIOBE Popular programming languages index (15th Consecutive Year)

What you will Learn in this Course?

Introduction to Java

• Java Fundamentals
• Introduction to Java Basics
• Features of Java
• Various components of Java language
• Benefits of Java over other programming languages
• Key Benefits of Java

Installation and IDE’s for Java Programming Language

• Installation of Java
• Setting up of Eclipse IDE
• Components of Java Program
• Editors and IDEs used for Java Programming
• Writing a Simple Java Program

Data Handling and Functions

• Data types, Operations, Compilation process, Class files, Loops, Conditions
• Using Loop Constructs
• Arrays- Single Dimensional and Multi-Dimensional
• Functions
• Functions with Arguments

OOPS in Java: Concept of Object Orientation

• Object Oriented Programming in Java
• Implement classes and objects in Java
• Create Class Constructors
• Overload Constructors
• Inheritance
• Inherit Classes and create sub-classes
• Implement abstract classes and methods
• Use static keyword
• Implement Interfaces and use it

Polymorphism, Packages and String Handling

• Concept of Static and Run time Polymorphism
• Function Overloading
• String Handling –String Class
• Java Packages

Exception Handling and Multi-Threading

• Exception handling
• Various Types of Exception Handling
• Introduction to multi-threading in Java
• Extending the thread class
• Synchronizing the thread

File Handling in Java

• Input Output Streams
• Java.io Package
• File Handling in Java

Java Collections

• Wrapper Classes and Inner Classes: Integer, Character, Boolean, Float etc
• Applet Programs: How to write UI programs with Applet, Java.lang, Java.io, Java.util
• Collections: ArrayList, Vector, HashSet, TreeSet, HashMap, HashTable

Java Database Connectivity (JDBC)

• Introduction to SQL: Connect, Insert, Update, Delete, Select
• Introduction to JDBC and Architecture of JDBC
• Insert/Update/Delete/Select Operations using JDBC
• Batch Processing Transaction
• Management: Commit and Rollback

Java Enterprise Edition – Servlets

• Introduction to J2EE
• Client Server architecture
• URL, Port Number, Request, Response
• Need for servlets
• Servlet fundamentals
• Setting up a web project in Eclipse
• Configuring and running the web app with servlets
• GET and POST request in web application with demo
• Servlet lifecycle
• Servlets Continued
• Session tracking and filter
• Forward and include Servlet request dispatchers

Java Server Pages (JSP)

• Fundamentals of Java Server Page
• Writing a code using JSP
• The architecture of JSP
• JSP Continued
• JSP elements: Scriptlets, expressions, declaration
• JSP standard actions
• JSP directives
• Introduction to JavaBeans
• ServletConfig and ServletContext
• Servlet Chaining
• Cookies Management
• Session Management

Hibernate

• Introduction to Hibernate
• Introduction to ORM
• ORM features
• Hibernate as an ORM framework
• Hibernate features
• Setting up a project with Hibernate framework
• Basic APIs needed to do CRUD operations with Hibernate
• Hibernate Architecture

POJO (Plain Old Java Object)

• POJO (Plain Old Java Object)
• Persistent Objects
• Lifecycle of Persistent Object

Spring

• Introduction to Spring
• Spring Fundamentals
• Advanced Spring

Got a question for us? Please mention it in the comments section and we will get back to you.

 

0 responses on "StringBuffer and StringBuilder Class in Java"

Leave a Message

Your email address will not be published. Required fields are marked *