0% found this document useful (0 votes)
53 views

StringBuffer Class

stringbuffer class

Uploaded by

msoren07322
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
53 views

StringBuffer Class

stringbuffer class

Uploaded by

msoren07322
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

Java Arrays Java Strings Java OOPs Java Collection Java 8 Tutorial Java Multithreading Java

StringBuffer class in Java


StringBuffer is a class in Java that represents a mutable sequence of
characters. It provides an alternative to the immutable String class,
allowing you to modify the contents of a string without creating a new
object every time.

Here are some important features and methods of the StringBuffer


class:

1. StringBuffer objects are mutable, meaning that you can change the
contents of the buffer without creating a new object.
2. The initial capacity of a StringBuffer can be specified when it is
created, or it can be set later with the ensureCapacity() method.
3. The append() method is used to add characters, strings, or other
objects to the end of the buffer.
4. The insert() method is used to insert characters, strings, or other
objects at a specified position in the buffer.
5. The delete() method is used to remove characters from the buffer.
6. The reverse() method is used to reverse the order of the characters
in the buffer.

Here is an example of using StringBuffer to concatenate strings:

Java

public class StringBufferExample {


publicto ensure
We use cookies static youvoid main(String[]
have the args) on our website. By using our site, you
best browsing experience
{acknowledge that you have read and understood our Cookie Policy & Privacy Policy
StringBuffer sb = new StringBuffer();
sb.append("Hello"); Got It !
sb.append(" ");
sb.append("world");
String message = sb.toString();
System.out.println(message);
}
}

Output

Hello world

There are several advantages of using StringBuffer over regular


String objects in Java:

1. Mutable: StringBuffer objects are mutable, which means that you


can modify the contents of the object after it has been created. In
contrast, String objects are immutable, which means that you
cannot change the contents of a String once it has been created.
2. Efficient: Because StringBuffer objects are mutable, they are more
efficient than creating new String objects each time you need to
modify a string. This is especially true if you need to modify a string
multiple times, as each modification to a String object creates a new
object and discards the old one.
3. Thread-safe: StringBuffer objects are thread-safe, which means
multiple threads can access it simultaneously( they can be safely
accessed and modified by multiple threads simultaneously). In
contrast, String objects are not thread-safe, which means that you
need to use synchronization if you want to access a String object
from multiple threads.

Overall, if you need to perform multiple modifications to a string, or if


you need to access a string from multiple threads, using StringBuffer
can be more efficient and safer than using regular String objects.

StringBuffer is a peer class of String that provides much of the


functionality of strings. The string represents fixed-length, immutable
character sequences while StringBuffer represents growable and
writable character sequences. StringBuffer may have characters and
substrings inserted in the middle or appended to the end. It will
automatically grow to make room for such additions and often has
more characters preallocated than are actually needed, to allow room
for growth.

StringBuffer class is used to create mutable (modifiable) strings. The


StringBuffer class in Java is the same as the String class except it is
mutable i.e. it can be changed.

Important Constructors of StringBuffer class


StringBuffer(): creates an empty string buffer with an 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.

1. append() method

The append() method concatenates the given argument with this


string.

Example:

Java

import java.io.*;

class A {
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("Hello ");
sb.append("Java"); // now original string is changed
System.out.println(sb);
}
}

Output

Hello Java

2. insert() method

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

Example:

Java

import java.io.*;

class A {
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("Hello ");
sb.insert(1, "Java");
// Now original string is changed
System.out.println(sb);
}
}

Output

HJavaello

3. replace() method

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

Example:

Java

import java.io.*;

class A {
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("Hello");
sb.replace(1, 3, "Java");
System.out.println(sb);
}
}

Output

HJavalo

4. delete() method

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

Example:
Java

import java.io.*;

class A {
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("Hello");
sb.delete(1, 3);
System.out.println(sb);
}
}

Output

Hlo

5. reverse() method

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


string.

Example:

Java

import java.io.* ;

class A {
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("Hello");
sb.reverse();
System.out.println(sb);
}
}

Output

olleH
6. capacity() method

The capacity() method of the StringBuffer class returns the current


capacity of the buffer. The default capacity of the buffer is 16. If the
number of characters increases from its current capacity, it increases
the capacity by (oldcapacity*2)+2.
For instance, if your current capacity is 16, it will be (16*2)+2=34.

Example:

Java

import java.io.*;

class A {
public static void main(String args[])
{
StringBuffer sb = new StringBuffer();
System.out.println(sb.capacity()); // default 16
sb.append("Hello");
System.out.println(sb.capacity()); // now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());
// Now (16*2)+2=34 i.e (oldcapacity*2)+2
}
}

Output

16
16
34

Some Interesting Facts about the StringBuffer class


Do keep the following points in the back of your mind:

java.lang.StringBuffer extends (or inherits from) Object class.


All Implemented Interfaces of StringBuffer class: Serializable,
Appendable, CharSequence.
public final class StringBuffer extends Object implements
Serializable, CharSequence, Appendable.
String buffers are safe for use by multiple threads. The methods can
be synchronized wherever necessary so that all the operations on
any particular instance behave as if they occur in some serial order.
Whenever an operation occurs involving a source sequence (such as
appending or inserting from a source sequence) this class
synchronizes only on the string buffer performing the operation, not
on the source.
It inherits some of the methods from the Object class which such as
clone(), equals(), finalize(), getClass(), hashCode(), notifies(),
notifyAll().

Remember: StringBuilder, J2SE 5 adds a new string class to


Java’s already powerful string handling capabilities. This new
class is called StringBuilder. It is identical to StringBuffer except
for one important difference: it is not synchronized, which means
that it is not thread-safe. The advantage of StringBuilder is faster
performance. However, in cases in which you are using
multithreading, you must use StringBuffer rather than
StringBuilder.

Constructors of StringBuffer class


1. StringBuffer(): It reserves room for 16 characters without
reallocation

StringBuffer s = new StringBuffer();

2. StringBuffer( int size): It accepts an integer argument that explicitly


sets the size of the buffer.

StringBuffer s = new StringBuffer(20);

3. StringBuffer(String str): It accepts a string argument that sets the


initial contents of the StringBuffer object and reserves room for 16
more characters without reallocation.

StringBuffer s = new StringBuffer("GeeksforGeeks");

Methods of Java StringBuffer class

Methods Action Performed

append() Used to add text at the end of the existing text.

The length of a StringBuffer can be found by the


length()
length( ) method

the total allocated capacity can be found by the


capacity()
capacity( ) method

This method returns the char value in this sequence


charAt()
at the specified index.

Deletes a sequence of characters from the invoking


delete()
object

Deletes the character at the index specified by the


deleteCharAt()
loc

Ensures capacity is at least equal to the given


ensureCapacity()
minimum.

insert() Inserts text at the specified index position

length() Returns the length of the string

reverse() Reverse the characters within a StringBuffer object


Methods Action Performed

Replace one set of characters with another set inside


replace()
a StringBuffer object

Note: Besides that, all the methods that are used in the String
class can also be used. These auxiliary methods are as follows:

Methods Description Syntax

ensureCapacit It is used to increase


y() the capacity of a
StringBuffer object.
The new capacity will
be set to either the
value we specify or void
twice the current ensureCapacity(int capacity)
capacity plus two (i.e.
capacity+2), whichever
is larger. Here,
capacity specifies the
size of the buffer.

appendCodeP This method appends


oint(int the string public StringBuffer
codePoint) representation of the appendCodePoint(int
codePoint argument to codePoint)
this sequence.

charAt(int This method returns


index) the char value in this
public char charAt(int index)
sequence at the
Methods Description Syntax

specified index.

IntStream This method returns a


chars() stream of int zero-
extending the char public IntStream chars()
values from this
sequence.

int This method returns


codePointAt(i the character (Unicode public int codePointAt(int
nt index) code point) at the index)
specified index.

int This method returns


codePointBef the character (Unicode public int
ore(int index) code point) before the codePointBefore(int index)
specified index.

int This method returns


codePointCou the number of Unicode
public int codePointCount(int
nt(int code points in the
beginIndex, int endIndex)
beginIndex, specified text range of

int endIndex) this sequence.

IntStream This method returns a


codePoints() stream of code point public IntStream
values from this codePoints()
sequence.
Methods Description Syntax

void
In this method, the
getChars(int
characters are copied public void getChars(int
srcBegin, int
from this sequence srcBegin, int srcEnd, char[]
srcEnd, char[]
into the destination dst, int dstBegin)
dst, int character array dst.
dstBegin)

int This method returns


indexOf(Strin the index within this public int indexOf(String str)
g str) string of the first public int indexOf(String str,
occurrence of the int fromIndex)
specified substring.

int This method returns


public int lastIndexOf(String
lastIndexOf(S the index within this
str)
tring str) string of the last
public int lastIndexOf(String
occurrence of the
str, int fromIndex)
specified substring.

int This method returns


offsetByCode the index within this
public int
Points(int sequence that is offset
offsetByCodePoints(int
index, int from the given index
index, int codePointOffset)
codePointOffs by codePointOffset
code points.
et)

void In this method, the


setCharAt(int character at the public void setCharAt(int
index, char specified index is set index, char ch)
ch) to ch.
Methods Description Syntax

void This method sets the


public void setLength(int
setLength(int length of the character
newLength)
newLength) sequence.

CharSequenc This method returns a


e new character public CharSequence
subSequence( sequence that is a subSequence(int start, int
int start, int subsequence of this end)

end) sequence.

String This method returns a


substring(int new String that
public String substring(int
start) contains a
start)
subsequence of
public String substring(int
characters currently
start,int end)
contained in this
character sequence.

String This method returns a


toString() string representing the public String toString()
data in this sequence.

void This method attempts


trimToSize() to reduce storage used
public void trimToSize()
for the character
sequence.

Above we only have discussed the most widely used methods


and do keep a tight bound around them as they are widely used
in programming geeks.
Examples of the above methods
Example 1: length() and capacity() Methods

Java

// Java Program to Illustrate StringBuffer class


// via length() and capacity() methods

// Importing I/O classes


import java.io.*;

// Main class
class GFG {

// main driver method


public static void main(String[] args)
{

// Creating and storing string by creating object of


// StringBuffer
StringBuffer s = new StringBuffer("GeeksforGeeks");

// Getting the length of the string


int p = s.length();

// Getting the capacity of the string


int q = s.capacity();

// Printing the length and capacity of


// above generated input string on console
System.out.println("Length of string GeeksforGeeks="
+ p);
System.out.println(
"Capacity of string GeeksforGeeks=" + q);
}
}

Output

Length of string GeeksforGeeks=13


Capacity of string GeeksforGeeks=29
Example 2: append()

It is used to add text at the end of the existing text.

Here are a few of its forms:

StringBuffer append(String str)


StringBuffer append(int num)

Java

// Java Program to Illustrate StringBuffer class


// via append() method

// Importing required classes


import java.io.*;

// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{
// Creating an object of StringBuffer class and
// passing random string
StringBuffer s = new StringBuffer("Geeksfor");

// Usage of append() method


s.append("Geeks");

// Returns GeeksforGeeks
System.out.println(s);

s.append(1);
// Returns GeeksforGeeks1
System.out.println(s);
}
}

Output

GeeksforGeeks
GeeksforGeeks1
Example 3: insert()

It is used to insert text at the specified index position.

Syntax: These are a few of its as follows:

StringBuffer insert(int index, String str)


StringBuffer insert(int index, char ch)

Here, the index specifies the index at which point the string will be
inserted into the invoking StringBuffer object.

Java

// Java Program to Illustrate StringBuffer class


// via insert() method

// Importing required I/O classes


import java.io.*;

// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{
// Creating an object of StringBuffer class
StringBuffer s = new StringBuffer("GeeksGeeks");

// Inserting element and position as an arguments


s.insert(5, "for");
// Returns GeeksforGeeks
System.out.println(s);

s.insert(0, 5);
// Returns 5GeeksforGeeks
System.out.println(s);

s.insert(3, true);
// Returns 5GetrueeksforGeeks
System.out.println(s);

s.insert(5, 41.35d);
// Returns 5Getr41.35ueeksforGeeks
System.out.println(s);
s.insert(8, 41.35f);
// Returns 5Getr41.41.3535ueeksforGeeks
System.out.println(s);

// Declaring and initializing character array


char geeks_arr[] = { 'p', 'a', 'w', 'a', 'n' };

// Inserting character array at offset 9


s.insert(2, geeks_arr);
// Returns 5Gpawanetr41.41.3535ueeksforGeeks
System.out.println(s);
}
}

Output

GeeksforGeeks
5GeeksforGeeks
5GetrueeksforGeeks
5Getr41.35ueeksforGeeks
5Getr41.41.3535ueeksforGeeks
5Gpawanetr41.41.3535ueeksforGeeks

Example 4: reverse( )

It can reverse the characters within a StringBuffer object using


reverse( ). This method returns the reversed object on which it was
called.

Java

// Java Program to Illustrate StringBuffer class


// via reverse() method

// Importing I/O classes


import java.io.*;

// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{
// Creating a string via creating
// object of StringBuffer class
StringBuffer s = new StringBuffer("GeeksGeeks");

// Invoking reverse() method


s.reverse();

// Returns "skeeGrofskeeG"
System.out.println(s);
}
}

Output

skeeGskeeG

Example 5: delete( ) and deleteCharAt()

It can delete characters within a StringBuffer by using the methods


delete( ) and deleteCharAt( ).The delete( ) method deletes a
sequence of characters from the invoking object. Here, the start
Index specifies the index of the first character to remove, and the end
Index specifies an index one past the last character to remove. Thus,
the substring deleted runs from start Index to endIndex–1. The
resulting StringBuffer object is returned. The deleteCharAt( ) method
deletes the character at the index specified by loc. It returns the
resulting StringBuffer object.

Syntax:

StringBuffer delete(int startIndex, int endIndex)


StringBuffer deleteCharAt(int loc)

Java

// Java Program to Illustrate StringBuffer class


// via delete() and deleteCharAt() Methods

// Importing I/O classes


import java.io.*;
// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{
StringBuffer s = new StringBuffer("GeeksforGeeks");

s.delete(0, 5);
// Returns forGeeks
System.out.println(s);

s.deleteCharAt(7);
// Returns forGeek
System.out.println(s);
}
}

Output

forGeeks
forGeek

Example 6: replace()

It can replace one set of characters with another set inside a


StringBuffer object by calling replace( ). The substring being replaced
is specified by the indexes start Index and endIndex. Thus, the
substring at start Index through endIndex–1 is replaced. The
replacement string is passed in str. The resulting StringBuffer object is
returned.

Syntax:

StringBuffer replace(int startIndex, int endIndex, String str)

Example

Java

// Java Program to Illustrate StringBuffer class


// via replace() method
// Importing I/O classes
import java.io.*;

// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{
StringBuffer s = new StringBuffer("GeeksforGeeks");
s.replace(5, 8, "are");

// Returns GeeksareGeeks
System.out.println(s);
}
}

Output

GeeksareGeeks

This article is contributed by Lokesh Todwal.

Feeling lost in the vast world of Backend Development? It's time for a
change! Join our Java Backend Development - Live Course and embark
on an exciting journey to master backend development efficiently and
on schedule.
What We Offer:

Comprehensive Course
Expert Guidance for Efficient Learning
Hands-on Experience with Real-world Projects
Proven Track Record with 100,000+ Successful Geeks

Last Updated : 26 Jul, 2023 218

Previous Next

Why Java Strings are Immutable? StringBuilder Class in Java with


Examples

Share your thoughts in the comments Add Your Comment

Similar Reads
equals() on String and StringBuffer objects in Java

StringBuffer insert() in Java

StringBuffer deleteCharAt() Method in Java with Examples

StringBuffer appendCodePoint() Method in Java with Examples

StringBuffer delete() Method in Java with Examples

StringBuffer replace() Method in Java with Examples

StringBuffer reverse() Method in Java with Examples

StringBuffer append() Method in Java with Examples

StringBuffer setLength() in Java with Examples

StringBuffer subSequence() in Java with Examples


L Lokesh Todwal

Article Tags : Java-lang package , java-StringBuffer , Java-Strings , Java


Practice Tags : Java, Java-Strings

Trending in News View More

10 Best Free Social Media Management and Marketing Apps for Android - 2024
10 Best Customer Database Software of 2024
How to Delete Whatsapp Business Account?
Discord vs Zoom: Select The Efficienct One for Virtual Meetings?
30 OOPs Interview Questions and Answers (2024)
A-143, 9th Floor, Sovereign Corporate
Tower, Sector-136, Noida, Uttar Pradesh -
201305

Company Explore
About Us Hack-A-Thons
Legal GfG Weekly Contest
Careers DSA in JAVA/C++
In Media Master System Design
Contact Us Master CP
Advertise with us GeeksforGeeks Videos
GFG Corporate Solution Geeks Community
Placement Training Program

Languages DSA
Python Data Structures
Java Algorithms
C++ DSA for Beginners
PHP Basic DSA Problems
GoLang DSA Roadmap
SQL Top 100 DSA Interview Problems
R Language DSA Roadmap by Sandeep Jain
Android Tutorial All Cheat Sheets
Tutorials Archive

Data Science & ML HTML & CSS


Data Science With Python HTML
Data Science For Beginner CSS
Machine Learning Tutorial Web Templates
ML Maths CSS Frameworks
Data Visualisation Tutorial Bootstrap
Pandas Tutorial Tailwind CSS
NumPy Tutorial SASS
NLP Tutorial LESS
Deep Learning Tutorial Web Design
Django Tutorial

Python Tutorial Computer Science


Python Programming Examples Operating Systems
Python Projects Computer Network
Python Tkinter Database Management System
Web Scraping Software Engineering
OpenCV Tutorial Digital Logic Design
Python Interview Question Engineering Maths

DevOps Competitive Programming


Git Top DS or Algo for CP
AWS Top 50 Tree
Docker Top 50 Graph
Kubernetes Top 50 Array
Azure Top 50 String
GCP Top 50 DP
DevOps Roadmap Top 15 Websites for CP

System Design JavaScript


High Level Design JavaScript Examples
Low Level Design TypeScript
UML Diagrams ReactJS
Interview Guide NextJS
Design Patterns AngularJS
OOAD NodeJS
System Design Bootcamp Lodash
Interview Questions Web Browser

Preparation Corner School Subjects


Company-Wise Recruitment Process Mathematics
Resume Templates Physics
Aptitude Preparation Chemistry
Puzzles Biology
Company-Wise Preparation Social Science
English Grammar
World GK

Management & Finance Free Online Tools


Management Typing Test
HR Management Image Editor
Finance Code Formatters
Income Tax Code Converters
Organisational Behaviour Currency Converter
Marketing Random Number Generator
Random Password Generator

More Tutorials GeeksforGeeks Videos


Software Development DSA
Software Testing Python
Product Management Java
SAP C++
SEO - Search Engine Optimization Data Science
Linux CS Subjects
Excel

@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved

You might also like