0% found this document useful (0 votes)
10 views4 pages

Java StringBuffer Class Overview

Uploaded by

anjali.snbp
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)
10 views4 pages

Java StringBuffer Class Overview

Uploaded by

anjali.snbp
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

Java StringBuffer class

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.

Important Constructors 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
Method Description
Type
is used to append the specified string with this string.
public
The append() method is overloaded like append(char),
synchronized append(String s)
append(boolean), append(int), append(float),
StringBuffer
append(double) etc.
is used to insert the specified string with this string at
public
insert(int offset, String the specified position. The insert() method is
synchronized
s) overloaded like insert(int, char), insert(int, boolean),
StringBuffer
insert(int, int), insert(int, float), insert(int, double) etc.
public
replace(int startIndex, is used to replace the string from specified startIndex
synchronized
int endIndex, String str) and endIndex.
StringBuffer
public
delete(int startIndex, int is used to delete the string from specified startIndex
synchronized
endIndex) and endIndex.
StringBuffer
public
synchronized reverse() is used to reverse the string.
StringBuffer
public int capacity() is used to return the current capacity.
ensureCapacity(int is used to ensure the capacity at least equal to the
public void
minimumCapacity) given minimum.
public char charAt(int index) is used to return the character at the specified position.
is used to return the length of the string i.e. total
public int length()
number of characters.
substring(int is used to return the substring from the specified
public String
beginIndex) beginIndex.
substring(int
is used to return the substring from the specified
public String beginIndex, int
beginIndex and endIndex.
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) StringBuffer append() 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. [Link]("Java");//now original string is changed
5. [Link](sb);//prints Hello Java
6. }
7. }

2) StringBuffer insert() 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. [Link](1,"Java");//now original string is changed
5. [Link](sb);//prints HJavaello
6. }
7. }

3) StringBuffer replace() 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. [Link](1,3,"Java");
5. [Link](sb);//prints HJavalo
6. }
7. }

4) StringBuffer delete() 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. [Link](1,3);
5. [Link](sb);//prints Hlo
6. }
7. }

5) StringBuffer reverse() 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. [Link]();
5. [Link](sb);//prints olleH
6. }
7. }

6) StringBuffer capacity() 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. [Link]([Link]());//default 16
5. [Link]("Hello");
6. [Link]([Link]());//now 16
7. [Link]("java is my favourite language");
8. [Link]([Link]());//now (16*2)+2=34 i.e (oldcapacity*2)+2
9. }
10.}

7) StringBuffer ensureCapacity() 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. [Link]([Link]());//default 16
5. [Link]("Hello");
6. [Link]([Link]());//now 16
7. [Link]("java is my favourite language");
8. [Link]([Link]());//now (16*2)+2=34 i.e (oldcapacity*2)+2
9. [Link](10);//now no change
[Link]([Link]());//now 34
[Link](50);//now (34*2)+2
[Link]([Link]());//now 70
13.}
14.}

Common questions

Powered by AI

The capacity() method in the StringBuffer class is crucial for understanding memory optimization because it reveals the current capacity of the buffer, helping developers estimate and manage memory usage. By knowing the current capacity, developers can proactively manage the buffer size, ensuring enough space for operations that increase string length, while avoiding excessive memory usage. This allows for optimal performance and resource management during string handling .

The StringBuffer class mitigates interruptions due to inadequate capacity through the ensureCapacity() method, which proactively enlarges capacity beyond the given threshold. If the current capacity is surpassed during an operation (like append()), it automatically increases by (oldCapacity * 2) + 2 to accommodate the new data, thus preventing execution halts due to insufficient space .

Both insert() and replace() methods of StringBuffer modify the contents of the buffer, but they serve different purposes. The insert() method adds the specified string at a particular index, shifting the existing characters to the right to accommodate the new string. In contrast, replace() substitutes the characters within a specified range with the new string, altering only the selected segment. These operations differ in terms of whether they add new characters or alter existing ones .

The design of the StringBuffer class accounts for multithreading by making its methods synchronized. This ensures that only one thread can modify the buffer's content at a time, which prevents data inconsistencies and race conditions in concurrent programming environments. This thread safety feature allows StringBuffer to operate predictably and securely in multithreaded applications, contrasting with StringBuilder, which is not synchronized .

The initial capacity of a StringBuffer object is 16. When the content of the StringBuffer exceeds this initial capacity, the capacity is increased by the formula (oldCapacity * 2) + 2. For instance, if the current capacity is 16 and it is exceeded, the new capacity becomes 34 .

The ensureCapacity(int minimumCapacity) method in the StringBuffer class serves to ensure that the buffer has a capacity of at least the specified minimum. If the current capacity is less than the minimumCapacity argument, the capacity is expanded to accommodate the minimum requirement. This involves increasing the capacity by (oldCapacity * 2) + 2 if necessary. This method prevents frequent reallocations of memory during multiple append operations, optimizing performance .

The reverse() method in the StringBuffer class reverses the sequence of characters in the buffer. When invoked on a StringBuffer containing "Hello", it alters the order of characters to produce the output "olleH" .

The append() and delete() methods showcase the mutable nature of StringBuffer by allowing modifications to the original string object. The append() method concatenates the specified string to the existing StringBuffer, altering the original content without creating a new object. Similarly, the delete() method removes a portion of the content between the specified indices, directly affecting the original buffer. Both methods highlight that StringBuffer objects can change state without generating new instances, supporting their mutable characteristic .

The StringBuffer class in Java differs from the String class mainly because it is mutable, meaning it can be changed, while the String class is immutable. This implies that the StringBuffer class can be modified without creating new objects, which is not the case with the String class. Additionally, StringBuffer is thread-safe as its methods are synchronized, meaning that multiple threads cannot access it simultaneously, ensuring safe usage in a multithreaded environment .

Method overloading in StringBuffer allows different versions of a method to accept varying parameter types, providing versatility in string manipulation. For example, the append() method is overloaded to accept data types such as char, boolean, int, float, double, etc. This enables the seamless concatenation of different data types into a string buffer without manual type conversion, enhancing coding efficiency and readability. Similarly, the insert() method is overloaded, offering tailored manipulation based on argument types .

You might also like