0% found this document useful (0 votes)
4 views10 pages

StringBuffer Class in Java - GeeksforGeeks

The StringBuffer class in Java represents a mutable sequence of characters, allowing modifications without creating new objects. It is thread-safe due to synchronized methods, making it suitable for multithreaded environments, but it has performance overhead compared to non-synchronized alternatives like StringBuilder. Key methods include append(), insert(), replace(), delete(), and reverse(), among others, which facilitate various string operations.

Uploaded by

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

StringBuffer Class in Java - GeeksforGeeks

The StringBuffer class in Java represents a mutable sequence of characters, allowing modifications without creating new objects. It is thread-safe due to synchronized methods, making it suitable for multithreaded environments, but it has performance overhead compared to non-synchronized alternatives like StringBuilder. Key methods include append(), insert(), replace(), delete(), and reverse(), among others, which facilitate various string operations.

Uploaded by

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

StringBuffer Class in Java

Last Updated : 27 May, 2026

StringBuffer class in Java represents a sequence of characters that can be modified, which
means we can change the content of the StringBuffer without creating a new object every time.
It represents a mutable sequence of characters.

Unlike String, we can modify the content of the StringBuffer without creating a new object.
All methods of StringBuffer are synchronized, making it safe to use in multithreaded
environments.
Ideal for scenarios with frequent modifications like append, insert, delete or replace
operations.

Example: Here is an example of using StringBuffer to concatenate strings.

public class Geeks {


public static void main(String[] args){

// Creating StringBuffer
StringBuffer s = new StringBuffer();

// Adding elements in StringBuffer


[Link]("Hello");
[Link](" ");
[Link]("world");

// String with the StringBuffer value


String str = [Link]();
[Link](str);
}
}

Output

Hello world
Interface Hierarchy Implemented by StringBuffer
The diagram shows the interfaces implemented by StringBuffer and illustrates its relationship
with Appendable, CharSequence, and Serializable in Java.

StringBuffer

Constructors of StringBuffer Class


StringBuffer(): It reserves room for 16 characters without reallocation
StringBuffer(int size): It accepts an integer argument that explicitly sets the size of the
buffer.
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.

Example:

public class Geeks {


public static void main(String[] args) {

// 1. Using default constructor


StringBuffer sb1 = new StringBuffer();
[Link]("Hello");
[Link]("Default Constructor: " + sb1);

// 2. Using constructor with specified capacity


StringBuffer sb2 = new StringBuffer(50);
[Link]("Java Programming");
[Link]("With Capacity 50: " + sb2);

// 3. Using constructor with String


StringBuffer sb3 = new StringBuffer("Welcome");
[Link](" to Java");
[Link]("With String: " + sb3);
}
}

Output

Default Constructor: Hello


With Capacity 50: Java Programming
With String: Welcome to Java

Implementation of Java StringBuffer Method

1. append() Method

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

import [Link].*;

class Geeks {
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("Hello ");
[Link]("Java"); // now original string is changed
[Link](sb);
}
}

Output

Hello Java

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

import [Link].*;

class Geeks {
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("Hello ");
[Link](1, "Java");

// Now original string is changed


[Link](sb);
}
}

Output

HJavaello

3. replace() Method

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

import [Link].*;

class Geeks {
public static void main(String args[]) {

StringBuffer sb = new StringBuffer("Hello");


[Link](1, 3, "Java");
[Link](sb);
}
}

Output

HJavalo

4. delete() Method
delete() method is used to delete the string from the specified beginIndex to endIndex-1.

import [Link].*;

class Geeks {
public static void main(String args[]) {

StringBuffer sb = new StringBuffer("Hello");


[Link](1, 3);
[Link](sb);
}
}

Output

Hlo

5. reverse() Method

reverse() method of the StringBuffer class reverses the current string.

import [Link].* ;

class Geeks {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("Hello");
[Link]();
[Link](sb);
}
}

Output

olleH

6. capacity() Method

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 example, if the current capacity is 16, it will be (16*2)+2=34.

import [Link].*;

class Geeks {
public static void main(String args[])
{
StringBuffer sb = new StringBuffer();

// default 16
[Link]([Link]());
[Link]("Hello");

// now 16
[Link]([Link]());
[Link]("java is my favourite language");

// (oldcapacity*2)+2
[Link]([Link]());
}
}

Output

16
16
34

7. length()

This method return the number of character in given string.

import [Link].*;

class Geeks {
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 = [Link]();

// Getting the capacity of the string


[Link]("Length of string GeeksforGeeks=" + p);
}
}

Output

Length of string GeeksforGeeks=13

Advantages:
Mutable: Its content can be modified after creation while String remains immutable.
Better for Repeated Updates: Frequent concatenations perform efficiently because no new
objects are created for each change.
Thread-Safe: All methods are synchronized, making it safe in multithreaded environments.

Limitations:
Performance Overhead: Synchronization makes operations slower compared to non-
synchronized alternatives.
Not Ideal for Single-Threaded Applications: When thread safety is unnecessary, it adds extra
processing cost.
Lower Performance Than StringBuilder: StringBuilder is preferred in non-threaded scenarios
because it is faster.

StringBuffer all Methods

Methods Description Syntax

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


[Link](String str);
text.
Methods Description Syntax

length() The length of a StringBuffer can be found by int len = [Link]();


the length( ) method.

capacity() the total allocated capacity can be found by


int cap = [Link]();
the capacity( ) method.

charAt() This method returns the char value in this char ch = [Link](int
sequence at the specified index. index);

delete() Deletes a sequence of characters from the [Link](int start, int end);
invoking object.

deleteCharAt() Deletes the character at the index specified


[Link](int index);
by the loc.

ensureCapacity() Ensures capacity is at least equal to the [Link](int


given minimum. minimumCapacity);

insert() [Link](int offset, String


Inserts text at the specified index position.
str);

reverse() Reverse the characters within a StringBuffer


[Link]();
object.

replace() Replace one set of characters with another [Link](int start, int end,
set inside a StringBuffer object. String str);

ensureCapacity() Increases StringBuffer capacity to the void


specified value ensureCapacity(int capacity)

appendCodePoint(int public StringBuffer


Appends code point as a string to the
codePoint) appendCodePoint(int
sequence.
codePoint)

charAt(int index) Returns the char at the specified index. public char charAt(int index)
Methods Description Syntax

IntStream chars() Returns a stream of int values from zero-


public IntStream chars()
extended chars in the sequence..

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

codePointBefore() Returns the Unicode code point before the public int
given index. codePointBefore(int index)

codePointCount() public int


Returns the count of Unicode code points in
codePointCount(int
the specified text range.
beginIndex, int endIndex)

IntStream Returns a stream of code points from the public IntStream


codePoints() sequence. codePoints()

getChars() public void getChars(int


Copies characters from the sequence into
srcBegin, int srcEnd, char[]
the destination array.
dst, int dstBegin)

indexOf() public int indexOf(String str)


Returns the index of the first occurrence of
public int indexOf(String str,
the specified substring.
int fromIndex)

lastIndexOf() public int lastIndexOf(String


Returns the index of the last occurrence of str)
the specified substring. public int lastIndexOf(String
str, int fromIndex)

offsetByCodePoints() Returns the index offset by a specified public int


number of code points from the given offsetByCodePoints(int
index.. index, int codePointOffset)

setCharAt() In this method, the character at the public void setCharAt(int


specified index is set to ch. index, char ch)
Methods Description Syntax

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

subSequence() public CharSequence


Returns index offset by given code points
subSequence(int start, int
from the specified index.
end)

substring() public String substring(int


Returns a new String containing a start)
subsequence of this character sequence. public String substring(int
start,int end)

toString() Returns a string representing the data in the


public String toString()
sequence.

trimToSize() Attempts to minimize storage used by the


public void trimToSize()
character sequence.

Suggested Quiz 4 Questions

Predict the output of the following program.

class Test
{
public static void main(String[] args)
{
StringBuffer a = new StringBuffer("geeks");
StringBuffer b = new StringBuffer("forgeeks");
[Link](1,3);
[Link](b);
[Link](a);
}
}

A gsforgeeks

B gksforgeeks

C geksforgeeks

You might also like