Skip to content
geeksforgeeks
Courses 90% Refund
Tutorials
Java
Practice
Contests
Sign In
Java Arrays
Java Strings
Java OOPs
Java Collection
Java 8 Tutorial
Java Multithreading
Java Exception Handling
Java Programs
Java Project
Java Collections Interview
Java Interview Questions
Java MCQs
Spring
Spring MVC
Spring Boot
Hibernate
Content Improvement Event
Share Your Experiences
Java Tutorial
Overview of Java
Basics of Java
Input/Output in Java
Flow Control in Java
Operators in Java
Strings in Java
Strings in Java
String class in Java
Java.lang.String class in Java | Set 2
Why Java Strings are Immutable?
StringBuffer class in Java
StringBuilder Class in Java with Examples
String vs StringBuilder vs StringBuffer in Java
StringTokenizer Class in Java
StringTokenizer Methods in Java with Examples | Set 2
StringJoiner Class in Java
Arrays in Java
OOPS in Java
Inheritance in Java
Abstraction in Java
Encapsulation in Java
Polymorphism in Java
Constructors in Java
Methods in Java
Interfaces in Java
Wrapper Classes in Java
Keywords in Java
Access Modifiers in Java
Memory Allocation in Java
Classes of Java
Packages in Java
Java Collection Tutorial
Exception Handling in Java
Multithreading in Java
Synchronization in Java
File Handling in Java
Java Regex
Java IO
Java Networking
JDBC - Java Database Connectivity
Java 8 Features - Complete Tutorial
Java Backend DevelopmentCourse
StringBuilder Class in Java with Examples
Last Updated : 14 Mar, 2023
StringBuilder in Java represents a mutable sequence of characters. Since the String
Class in Java creates an immutable sequence of characters, the StringBuilder class
provides an alternative to String Class, as it creates a mutable sequence of
characters. The function of StringBuilder is very much similar to the StringBuffer
class, as both of them provide an alternative to String Class by making a mutable
sequence of characters. However, the StringBuilder class differs from the
StringBuffer class on the basis of synchronization. The StringBuilder class
provides no guarantee of synchronization whereas the StringBuffer class does.
Therefore this class is designed for use as a drop-in replacement for StringBuffer
in places where the StringBuffer was being used by a single thread (as is generally
the case). Where possible, it is recommended that this class be used in preference
to StringBuffer as it will be faster under most implementations. Instances of
StringBuilder are not safe for use by multiple threads. If such synchronization is
required then it is recommended that StringBuffer be used. String Builder is not
thread-safe and high in performance compared to String buffer.
The class hierarchy is as follows:
java.lang.Object
↳ java.lang
↳ Class StringBuilder
Syntax:
public final class StringBuilder
extends Object
implements Serializable, CharSequence
Constructors in Java StringBuilder Class
StringBuilder(): Constructs a string builder with no characters in it and an
initial capacity of 16 characters.
StringBuilder(int capacity): Constructs a string builder with no characters in it
and an initial capacity specified by the capacity argument.
StringBuilder(CharSequence seq): Constructs a string builder that contains the same
characters as the specified CharSequence.
StringBuilder(String str): Constructs a string builder initialized to the contents
of the specified string.
Below is a sample program to illustrate StringBuilder in Java.
// Java Code to illustrate StringBuilder
import java.util.*;
import java.util.concurrent.LinkedBlockingQueue;
public class GFG1 {
public static void main(String[] argv) throws Exception
{
// Create a StringBuilder object
// using StringBuilder() constructor
StringBuilder str = new StringBuilder();
str.append("GFG");
// print string
System.out.println("String = " + str.toString());
// create a StringBuilder object
// using StringBuilder(CharSequence) constructor
StringBuilder str1
= new StringBuilder("AAAABBBCCCC");
// print string
System.out.println("String1 = " + str1.toString());
// create a StringBuilder object
// using StringBuilder(capacity) constructor
StringBuilder str2 = new StringBuilder(10);
// print string
System.out.println("String2 capacity = "
+ str2.capacity());
// create a StringBuilder object
// using StringBuilder(String) constructor
StringBuilder str3
= new StringBuilder(str1.toString());
// print string
System.out.println("String3 = " + str3.toString());
}
}
Output
String = GFG
String1 = AAAABBBCCCC
String2 capacity = 10
String3 = AAAABBBCCCC
Methods in Java StringBuilder
StringBuilder append(X x): This method appends the string representation of the X
type argument to the sequence.
StringBuilder appendCodePoint(int codePoint): This method appends the string
representation of the codePoint argument to this sequence.
int capacity(): This method returns the current capacity.
char charAt(int index): This method returns the char value in this sequence at the
specified index.
IntStream chars(): This method returns a stream of int zero-extending the char
values from this sequence.
int codePointAt(int index): This method returns the character (Unicode code point)
at the specified index.
int codePointBefore(int index): This method returns the character (Unicode code
point) before the specified index.
int codePointCount(int beginIndex, int endIndex): This method returns the number of
Unicode code points in the specified text range of this sequence.
IntStream codePoints(): This method returns a stream of code point values from this
sequence.
StringBuilder delete(int start, int end): This method removes the characters in a
substring of this sequence.
StringBuilder deleteCharAt(int index): This method removes the char at the
specified position in this sequence.
void ensureCapacity(int minimumCapacity): This method ensures that the capacity is
at least equal to the specified minimum.
void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin): This method
characters are copied from this sequence into the destination character array dst.
int indexOf(): This method returns the index within this string of the first
occurrence of the specified substring.
StringBuilder insert(int offset, boolean b): This method inserts the string
representation of the boolean alternate argument into this sequence.
StringBuilder insert(): This method inserts the string representation of the char
argument into this sequence.
int lastIndexOf(): This method returns the index within this string of the last
occurrence of the specified substring.
int length(): This method returns the length (character count).
int offsetByCodePoints(int index, int codePointOffset): This method returns the
index within this sequence that is offset from the given index by codePointOffset
code points.
StringBuilder replace(int start, int end, String str): This method replaces the
characters in a substring of this sequence with characters in the specified String.
StringBuilder reverse(): This method causes this character sequence to be replaced
by the reverse of the sequence.
void setCharAt(int index, char ch): In this method, the character at the specified
index is set to ch.
void setLength(int newLength): This method sets the length of the character
sequence.
CharSequence subSequence(int start, int end): This method returns a new character
sequence that is a subsequence of this sequence.
String substring(): This method returns a new String that contains a subsequence of
characters currently contained in this character sequence.
String toString(): This method returns a string representing the data in this
sequence.
void trimToSize(): This method attempts to reduce storage used for the character
sequence.
Example:
// Java code to illustrate
// methods of StringBuilder
import java.util.*;
import java.util.concurrent.LinkedBlockingQueue;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
// create a StringBuilder object
// with a String pass as parameter
StringBuilder str
= new StringBuilder("AAAABBBCCCC");
// print string
System.out.println("String = "
+ str.toString());
// reverse the string
StringBuilder reverseStr = str.reverse();
// print string
System.out.println("Reverse String = "
+ reverseStr.toString());
// Append ', '(44) to the String
str.appendCodePoint(44);
// Print the modified String
System.out.println("Modified StringBuilder = "
+ str);
// get capacity
int capacity = str.capacity();
// print the result
System.out.println("StringBuilder = " + str);
System.out.println("Capacity of StringBuilder = "
+ capacity);
}
}
Output
String = AAAABBBCCCC
Reverse String = CCCCBBBAAAA
Modified StringBuilder = CCCCBBBAAAA,
StringBuilder = CCCCBBBAAAA,
Capacity of StringBuilder = 27
StringBuilder is another class in Java that is used to manipulate strings. Like
StringBuffer, it is a mutable class that allows you to modify the contents of the
string it represents. However, StringBuilder is not thread-safe, so it should not
be used in a multi-threaded environment.
Here are some examples of how to use StringBuilder in Java:
public class StringBuilderExample {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(" ");
sb.append("world!");
System.out.println(sb.toString()); // Output: "Hello world!"
sb.insert(6, "beautiful ");
System.out.println(sb.toString()); // Output: "Hello beautiful world!"
sb.reverse();
System.out.println(sb.toString()); // Output: "!dlrow lufituaeb olleH"
}
}
Output
Hello world!
Hello beautiful world!
!dlrow lufituaeb olleH
Three 90 Challenge is back on popular demand! After processing refunds worth INR
1CR+, we are back with the offer if you missed it the first time. Get 90% course
fee refund in 90 days. Avail now!
Want to be a master in Backend Development with Java for building robust and
scalable applications? Enroll in Java Backend and Development Live Course by
GeeksforGeeks to get your hands dirty with Backend Programming. Master the key Java
concepts, server-side programming, database integration, and more through hands-on
experiences and live projects. Are you new to Backend development or want to be a
Java Pro? This course equips you with all you need for building high-performance,
heavy-loaded backend systems in Java. Ready to take your Java Backend skills to the
next level? Enroll now and take your development career to sky highs.
RishabhPrabhu
175
Previous Article
StringBuffer class in Java
Next Article
String vs StringBuilder vs StringBuffer in Java
Read More
Down Arrow
Similar Reads
StringBuilder charAt() in Java with Examples
The charAt(int index) method of StringBuilder Class is used to return the character
at the specified index of String contained by StringBuilder Object. The index value
should lie between 0 and length()-1. Syntax: public char charAt(int index)
Parameters: This method accepts one int type parameter index which represents index
of the character to be
3 min read
StringBuilder codePointAt() in Java with Examples
The codePointAt(int index) method of StringBuilder class takes an index as a
parameter and returns a character unicode point at that index in String contained
by StringBuilder or we can say charPointAt() method returns the "unicode number" of
the character at that index. The index refers to char values (Unicode code units)
and the value of index mu
4 min read
StringBuilder append() Method in Java With Examples
The java.lang.StringBuilder.append() method is used to append the string
representation of some argument to the sequence. There are 13 ways/forms in which
the append() method can be used by the passing of various types of arguments:
StringBuilder append(boolean a) :The java.lang.StringBuilder.append(boolean a) is
an inbuilt method in Java which is
13 min read
StringBuilder delete() in Java with Examples
The delete(int start, int end) method of StringBuilder class removes the characters
starting from index start to index end-1 from String contained by StringBuilder.
This method takes two indexes as a parameter first start represents index of the
first character and endIndex represents index after the last character of the
substring to be removed fr
3 min read
StringBuilder codePointCount() in Java with Examples
The codePointCount() method of StringBuilder class returns the number of Unicode
code points in the specified text range in String contained by StringBuilder. This
method takes two indexes as a parameter- first beginIndex which represents index of
the first character of the text range and endIndex which represents index after the
last character of
3 min read
StringBuilder capacity() in Java with Examples
The capacity() method of StringBuilder Class is used to return the current capacity
of StringBUilder object. The capacity is the amount of storage available to insert
new characters.Syntax: public int capacity() Return Value: This method returns the
current capacity of StringBuilder Class.Below programs demonstrate the capacity()
method of StringBu
2 min read
StringBuilder codePointBefore() in Java with Examples
The codePointBefore() method of StringBuilder class takes an index as a parameter
and returns the "Unicode number" of the character before the specified index in
String contained by StringBuilder. The index refers to char values (Unicode code
units) and the value of index must lie between 0 to length-1. If the char value at
(index - 1) is in the lo
2 min read
StringBuilder deleteCharAt() in Java with Examples
The deleteCharAt(int index) method of StringBuilder class remove the character at
the given index from String contained by StringBuilder. This method takes index as
a parameter which represents the index of char we want to remove and returns the
remaining String as StringBuilder Object. This StringBuilder is shortened by one
char after application
3 min read
StringBuilder ensureCapacity() in Java with Examples
The ensureCapacity(int minimumCapacity) method of StringBuilder class helps us to
ensures the capacity is at least equal to the specified minimumCapacity passed as
the parameter to the method. If the current capacity of StringBuilder is less than
the argument minimumCapacity, then a new internal array is allocated with greater
capacity. If the mini
2 min read
StringBuilder getChars() in Java with Examples
The getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) method of
StringBuilder class copies the characters starting at the given index:srcBegin to
index:srcEnd-1 from String contained by StringBuilder into an array of char passed
as parameter to function. The characters are copied from StringBuilder into the
array dst[] starting at index:
3 min read
Article Tags :
Java
Java-Class and Object
Java-lang package
Java-StringBuilder
Practice Tags :
Java
Java-Class and Object
three90RightbarBannerImg
course-img
214k+ interested Geeks
JAVA Backend Development - Live
Explore
course-img
30k+ interested Geeks
Manual to Automation Testing: A QA Engineer's Guide
Explore
course-img
216k+ interested Geeks
Java Programming Online Course [Complete Beginner to Advanced]
Explore
geeksforgeeks-footer-logo
Corporate & Communications Address:- A-143, 9th Floor, Sovereign Corporate Tower,
Sector- 136, Noida, Uttar Pradesh (201305) | Registered Address:- K 061, Tower K,
Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh,
201305
GFG App on Play Store
GFG App on App Store
Company
About Us
Legal
Careers
In Media
Contact Us
Advertise with us
GFG Corporate Solution
Placement Training Program
Explore
Job-A-Thon Hiring Challenge
Hack-A-Thon
GfG Weekly Contest
Offline Classes (Delhi/NCR)
DSA in JAVA/C++
Master System Design
Master CP
GeeksforGeeks Videos
Geeks Community
Languages
Python
Java
C++
PHP
GoLang
SQL
R Language
Android Tutorial
DSA
Data Structures
Algorithms
DSA for Beginners
Basic DSA Problems
DSA Roadmap
DSA Interview Questions
Competitive Programming
Data Science & ML
Data Science With Python
Data Science For Beginner
Machine Learning Tutorial
ML Maths
Data Visualisation Tutorial
Pandas Tutorial
NumPy Tutorial
NLP Tutorial
Deep Learning Tutorial
Web Technologies
HTML
CSS
JavaScript
TypeScript
ReactJS
NextJS
NodeJs
Bootstrap
Tailwind CSS
Python Tutorial
Python Programming Examples
Django Tutorial
Python Projects
Python Tkinter
Web Scraping
OpenCV Tutorial
Python Interview Question
Computer Science
GATE CS Notes
Operating Systems
Computer Network
Database Management System
Software Engineering
Digital Logic Design
Engineering Maths
DevOps
Git
AWS
Docker
Kubernetes
Azure
GCP
DevOps Roadmap
System Design
High Level Design
Low Level Design
UML Diagrams
Interview Guide
Design Patterns
OOAD
System Design Bootcamp
Interview Questions
School Subjects
Mathematics
Physics
Chemistry
Biology
Social Science
English Grammar
Commerce
Accountancy
Business Studies
Economics
Management
HR Management
Finance
Income Tax
Databases
SQL
MYSQL
PostgreSQL
PL/SQL
MongoDB
Preparation Corner
Company-Wise Recruitment Process
Resume Templates
Aptitude Preparation
Puzzles
Company-Wise Preparation
Companies
Colleges
Competitive Exams
JEE Advanced
UGC NET
UPSC
SSC CGL
SBI PO
SBI Clerk
IBPS PO
IBPS Clerk
More Tutorials
Software Development
Software Testing
Product Management
Project Management
Linux
Excel
All Cheat Sheets
Recent Articles
Free Online Tools
Typing Test
Image Editor
Code Formatters
Code Converters
Currency Converter
Random Number Generator
Random Password Generator
Write & Earn
Write an Article
Improve an Article
Pick Topics to Write
Share your Experiences
Internships
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By
using our site, you acknowledge that you have read and understood our Cookie Policy
& Privacy Policy
Got It !
Lightbox