0% found this document useful (0 votes)
16 views12 pages

Skip To Contentb

Uploaded by

raroy67751
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views12 pages

Skip To Contentb

Uploaded by

raroy67751
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 12

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
String vs StringBuilder vs StringBuffer in Java
Last Updated : 02 Apr, 2024
A string is a sequence of characters. In Java, objects of String are immutable
which means a constant and cannot be changed once created. Initializing a String is
one of the important pillars required as a pre-requisite with deeper understanding.

Comparison between String, StringBuilder, and StringBuffer


Feature

String

StringBuilder

StringBuffer

Introduction

Introduced in JDK 1.0

Introduced in JDK 1.5

Introduced in JDK 1.0

Mutability

Immutable

Mutable

Mutable

Thread Safety

Thread Safe

Not Thread Safe

Thread Safe

Memory Efficiency

High

Efficient
Less Efficient

Performance

High(No-Synchronization)

High(No-Synchronization)

Low(Due to Synchronization)

Usage

This is used when we want immutability.

This is used when Thread safety is not required.

This is used when Thread safety is required.

Now, we will be justifying. Let us do consider the below code with three
concatenation functions with three different types of parameters, String,
StringBuffer, and StringBuilder. Let us clear out the understanding between them
via a single Java program below from which we will be drawing out conclusions from
the output generated, to figure out differences between String vs StringBuilder vs
StringBuffer in Java.

Example

// Java program to demonstrate difference between


// String, StringBuilder and StringBuffer

// Main class
class GFG {

// Method 1
// Concatenates to String
public static void concat1(String s1)
{
s1 = s1 + "forgeeks";
}

// Method 2
// Concatenates to StringBuilder
public static void concat2(StringBuilder s2)
{
s2.append("forgeeks");
}

// Method 3
// Concatenates to StringBuffer
public static void concat3(StringBuffer s3)
{
s3.append("forgeeks");
}

// Method 4
// Main driver method
public static void main(String[] args)
{
// Custom input string
// String 1
String s1 = "Geeks";

// Calling above defined method


concat1(s1);

// s1 is not changed
System.out.println("String: " + s1);

// String 1
StringBuilder s2 = new StringBuilder("Geeks");

// Calling above defined method


concat2(s2);

// s2 is changed
System.out.println("StringBuilder: " + s2);

// String 3
StringBuffer s3 = new StringBuffer("Geeks");

// Calling above defined method


concat3(s3);

// s3 is changed
System.out.println("StringBuffer: " + s3);
}
}

Output
String: Geeks
StringBuilder: Geeksforgeeks
StringBuffer: Geeksforgeeks
Output explanation:

Concat1: In this method, we pass a string “Geeks” and perform “s1 = s1 +


”forgeeks”. The string passed from main() is not changed, this is due to the fact
that String is immutable. Altering the value of string creates another object and
s1 in concat1() stores reference of the new string. References s1 in main() and
cocat1() refer to different strings.
Concat2: In this method, we pass a string “Geeks” and perform
“s2.append(“forgeeks”)” which changes the actual value of the string (in main) to
“Geeksforgeeks”. This is due to the simple fact that StringBuilder is mutable and
hence changes its value.
Concat3: StringBuilder is similar and can be compatible at all places to
StringBuffer except for the key difference of thread safety. StringBuffer is
thread-safe while StringBuilder does not guarantee thread safety which means
synchronized methods are present in StringBuffer making control of one thread
access at a time while it is not seen in StringBuilder, hence thread-unsafe.

Note: Geeks now you must be wondering when to use which one, do refer below as
follows:

If a string is going to remain constant throughout the program, then use the String
class object because a String object is immutable.
If a string can change (for example: lots of logic and operations in the
construction of the string) and will only be accessed from a single thread, using a
StringBuilder is good enough.
If a string can change and will be accessed from multiple threads, use a
StringBuffer because StringBuffer is synchronous, so you have thread-safety.
If you don’t want thread-safety than you can also go with StringBuilder class as it
is not synchronized.
Conversion between types of strings in Java
Sometimes there is a need for converting a string object of different classes like
String, StringBuffer, StringBuilder to one another. Below are some techniques to do
the same. Let us do cover all use cases s follows:

From String to StringBuffer and StringBuilder


From StringBuffer and StringBuilder to String
From StringBuffer to StringBuilder or vice-versa
Case 1: From String to StringBuffer and StringBuilder
This one is an easy way out as we can directly pass the String class object to
StringBuffer and StringBuilder class constructors. As the String class is immutable
in java, so for editing a string, we can perform the same by converting it to
StringBuffer or StringBuilder class objects.

Example

// Java program to demonstrate conversion from


// String to StringBuffer and StringBuilder

// Main class
public class GFG {

// Main driver method


public static void main(String[] args)
{
// Custom input string
String str = "Geeks";

// Converting String object to StringBuffer object


// by
// creating object of StringBuffer class
StringBuffer sbr = new StringBuffer(str);

// Reversing the string


sbr.reverse();

// Printing the reversed string


System.out.println(sbr);

// Converting String object to StringBuilder object


StringBuilder sbl = new StringBuilder(str);

// Adding it to string using append() method


sbl.append("ForGeeks");

// Print and display the above appended string


System.out.println(sbl);
}
}

Output
skeeG
GeeksForGeeks
Case 2: From StringBuffer and StringBuilder to String
This conversion can be performed using toString() method which is overridden in
both StringBuffer and StringBuilder classes.
Below is the java program to demonstrate the same. Note that while we use
toString() method, a new String object(in Heap area) is allocated and initialized
to the character sequence currently represented by the StringBuffer object, which
means the subsequent changes to the StringBuffer object do not affect the contents
of the String object.

Example

// Java Program to Demonstrate Conversion from


// String to StringBuffer and StringBuilder

// Main class
public class GFG {

// Main driver method


public static void main(String[] args)
{
// Creating objects of StringBuffer class
StringBuffer sbr = new StringBuffer("Geeks");
StringBuilder sbdr = new StringBuilder("Hello");

// Converting StringBuffer object to String


// using toString() method
String str = sbr.toString();

// Printing the above string


System.out.println(
"StringBuffer object to String : ");
System.out.println(str);

// Converting StringBuilder object to String


String str1 = sbdr.toString();

// Printing the above string


System.out.println(
"StringBuilder object to String : ");
System.out.println(str1);

// Changing StringBuffer object sbr


// but String object(str) doesn't change
sbr.append("ForGeeks");

// Printing the above two strings on console


System.out.println(sbr);
System.out.println(str);
}
}

Output
StringBuffer object to String :
Geeks
StringBuilder object to String :
Hello
GeeksForGeeks
Geeks
Case 3: From StringBuffer to StringBuilder or vice-versa
This conversion is tricky. There is no direct way to convert the same. In this
case, We can use a String class object. We first convert the
StringBuffer/StringBuilder object to String using toString() method and then from
String to StringBuilder/StringBuffer using constructors.

Example

// Java program to Demonstrate conversion from


// String to StringBuffer and StringBuilder

// Main class
public class GFG {

// Main driver method


public static void main(String[] args)
{
// Creating object of StringBuffer class and
// passing our input string to it
StringBuffer sbr = new StringBuffer("Geeks");

// Storing value StringBuffer object in String and


// henceforth converting StringBuffer object to
// StringBuilder class
String str = sbr.toString();
StringBuilder sbl = new StringBuilder(str);

// Printing the StringBuilder object on console


System.out.println(sbl);
}
}

Output
Geeks
From the above three use-cases we can conclude out below pointers:

Objects of String are immutable, and objects of StringBuffer and StringBuilder are
mutable.
StringBuffer and StringBuilder are similar, but StringBuilder is faster and
preferred over StringBuffer for the single-threaded program. If thread safety is
needed, then StringBuffer is used.
Related Article: Reverse a String in Java (5 Different Ways)

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.

Pranjal and Gaurav Miglani


151
Previous Article
StringBuilder Class in Java with Examples
Next Article
StringTokenizer Class in Java
Read More
Down Arrow
Similar Reads
Difference Between StringBuffer and StringBuilder in Java
Strings in Java are the objects that are backed internally by a char array. Since
arrays are immutable(cannot grow), Strings are immutable as well. Whenever a change
to a String is made, an entirely new String is created. However, java provides
multiple classes through which strings can be used. Two such classes are
StringBuffer and StringBuilder.
4 min read
equals() on String and StringBuffer objects in Java
Consider the following codes in java: Java Code // This program prints false class
GFG { public static void main(String[] args) { StringBuffer sb1 = new
StringBuffer("GFG"); StringBuffer sb2 = new
StringBuffer("GFG"); System.out.println(sb1.equals(sb2)); } } Output:
false Java Code // This program prints true class GFG { public
2 min read
Matcher appendReplacement(StringBuffer, String) method in Java with Examples
The appendReplacement(StringBuffer, String) method of Matcher Class behaves as a
append-and-replace method. This method reads the input string and replace it with
the matched pattern in the matcher string. Syntax: public Matcher
appendReplacement(StringBuffer buffer, String stringToBeReplaced) Parameters: This
method takes two parameters: buffer: w
3 min read
Sorting collection of String and StringBuffer in Java
Sorting a collection of objects can be done in two ways: By implementing Comparable
(Natural Order) e.g. Strings are sorted ASCIIbetically. meaning B comes before A
and 10 is before 2.By implementing Comparator (Custom order) and it can be in any
order.Using Collections.sort() method of Collections utility class. Read more about
Comparable and Comp
2 min read
Matcher appendReplacement(StringBuilder, String) method in Java with Examples
The appendReplacement(StringBuilder, String) method of Matcher Class behaves as a
append-and-replace method. This method reads the input string and replace it with
the matched pattern in the matcher string. Syntax: public Matcher
appendReplacement(StringBuilder builder, String stringToBeReplaced) Parameters:
This method takes two parameters: builde
3 min read
StringBuffer insert() in Java
The StringBuffer.insert() method inserts the string representation of given data
type at given position in a StringBuffer. Syntax: str.insert(int position, char x);
str.insert(int position, boolean x); str.insert(int position, char[] x);
str.insert(int position, float x); str.insert(int position, double x);
str.insert(int position, long x); str.ins
4 min read
StringBuffer deleteCharAt() Method in Java with Examples
The Java.lang.StringBuffer.deleteCharAt() is a built-in Java method which removes
the char at the specified position in this sequence. So that the sequence is
reduced by 1 char. Syntax: public StringBuffer deleteCharAt(int indexpoint)
Parameters : The method accepts a single parameter indexpoint of integer type which
refers to the index of the char
2 min read
StringBuffer appendCodePoint() Method in Java with Examples
appendCodePoint() method of StringBuffer class appends the string representation of
the codePoint argument to this sequence for which we require pre-requisite
knowledge of ASCII table as then only we will be able to perceive output why the
specific literal is being appended as there is already an integer value been
assigned. --> appendCodePoint(
3 min read
StringBuffer delete() Method in Java with Examples
The java.lang.StringBuffer.delete() is an inbuilt method in Java which is used to
remove or delete the characters in a substring of this sequence. The substring
starts at a specified index start_point and extends to the character at the index
end_point. Syntax : public StringBuffer delete(int start_point, int end_point)
Parameters : The method acce
3 min read
StringBuffer replace() Method in Java with Examples
The StringBuffer.replace() is the inbuilt method which is used to replace the
characters in a substring of this sequence with the characters in the specified
String. Here simply the characters in the substring are removed and other char is
inserted at the start.Syntax : public StringBuffer replace(int first, int last,
String st) Parameters : The me
2 min read
Article Tags :
Difference Between
Java
java-StringBuffer
Java-StringBuilder
+1 More
Practice Tags :
Java
Java-Strings
three90RightbarBannerImg
course-img
215k+ interested Geeks
Master Java Programming - Complete Beginner to Advanced
Avail 90% Refund
course-img
214k+ interested Geeks
JAVA Backend Development - Live
Avail 90% Refund
course-img
30k+ interested Geeks
Manual to Automation Testing: A QA Engineer's Guide
Avail 90% Refund
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

You might also like