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

StringBuffer Vs StringBuilder

StringBuffer provides similar functionality to strings but is mutable and growable, allowing existing objects to be modified. It overcomes the immutability of strings by creating strings of flexible length that can be modified in both length and content. StringBuffer is more memory efficient than strings when multiple modifications are made because it modifies the existing object rather than creating new objects.

Uploaded by

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

StringBuffer Vs StringBuilder

StringBuffer provides similar functionality to strings but is mutable and growable, allowing existing objects to be modified. It overcomes the immutability of strings by creating strings of flexible length that can be modified in both length and content. StringBuffer is more memory efficient than strings when multiple modifications are made because it modifies the existing object rather than creating new objects.

Uploaded by

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

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

functionality of strings. It provides more flexibility than String.


As we know that a string is fixed-length, immutable, and cannot be modified.
That is, once we create a String object, we cannot change its content.
To overcome this, Java language introduced another class called StringBuffer.
Java StringBuffer represents a growable nature and mutable. That means that
once we create a StringBuffer class object, we can perform any required
changes in the object. i.e, its data can be modified.
That’s why StringBuffer class objects are mutable in Java. It creates
strings of flexible length that can be modified in terms of both length and
content. That’s why StringBuffer is more flexible than String.
The methods of string buffer class can directly manipulate data inside the
object. We can easily insert characters and substrings in the middle of the
string or add another string to the end. StringBuffer can automatically expand
to create room for such additions.
StringBuffer class method is synchronized. Therefore, it is a thread-safe class
but it is slower than string.
In Fig 1, we have created a string object with the content “Hello”. Once we
create a string object with content, there is no chance to change its content
because the string object is immutable.
That means if we cannot change its content, the length of content “Hello” is
fixed i.e. 5 and its capacity is also 5 because we cannot add new characters.
Therefore, in the string, the terminology length and capacity both are the
same. Therefore, string never uses the terminology “capacity“.
But in the case of StringBuffer, there is a small difference between length and
capacity.
Capacity: The total number of characters hold in the StringBuffer object is
called capacity.
Length: The number of characters already present in the StringBuffer object
is called length.
In Fig 2, we have created a StringBuffer object with the same content. In the
case of StringBuffer, the length of the content “Hello” is also 5.
But is it possible to add some more characters to the existing object or not?
Yes, we can also add characters in the existing object because the capacity of
StringBuffer is not full. Here, the capacity is not 5.
Realtime Example:
Assume that there is a classroom. In the classroom, the capacity of classroom
is 100. That is the total number of students who can sit in the classroom is
100.
But currently, only 20 students are there. So, many seats are vacant. If the
classroom is considered as StringBuffer, length is 20 and capacity is 100. We
can add 80 more students to the classroom. That means we can add 80
characters more in the existing object.

How to create StringBuffer Objects in Java

There are mainly three ways to create StringBuffer objects in Java. Let’s
understand them one by one.
First way:
The first way for creating a StringBuffer object is that first allocate the memory
for the StringBuffer object by using the new operator and then store the string
into it.

The general syntax to create a string buffer object is as follows:


StringBuffer sb = new StringBuffer();

Here, we have created an empty StringBuffer object with a default initial


capacity of 16 characters and not passing any string to it.
To store a string into it, we can use append() method like this.
sb.append("Hello");

Now suppose 16 characters are completed. Can we add 17th character in


the existing StringBuffer object?
Yes, if the StringBuffer object is full, still we can add 17th character to it. Once
the capacity of StringBuffer object is filled, a new StringBuffer object will be
created with bigger capacity.
All the 16th characters will be copied plus 17th character will be added. The
reference variable sb will point to the new object and the old object by default
will be gone to the garbage collector. But these total things will happen
internally.

Q. What is the new capacity of a new StringBuffer object?


Ans: The capacity of a new StringBuffer object can be calculated by using the
formula below:
New capacity = ( Current capacity + 1 ) * 2
Thus, New capacity = (16 + 1) * 2 = 34

Once the 16th character is completed, the next capacity will be 34 if we add
17th character.

Let’s take an example program based on it. Look at the program source code
to understand better.
Program source code 1:
package stringBufferPrograms;
public class CapacityTest {
public static void main(String[ ] args)
{
// Create a StringBuffer object.
StringBuffer sb = new StringBuffer();
int length = sb.length();
int capacity = sb.capacity();

System.out.println("Before adding any character:");


System.out.println("Length = " +length); // length = 0
System.out.println("Default initial capacity = " +capacity); // Capacity = 16

// Adding 16 characters in the existing string buffer object.


sb.append("abcdefghijklmnop");
System.out.println("After adding 16 characters:");
System.out.println("Length = " +sb.length()); // now length is 16.
System.out.println("Capacity = " +sb.capacity()); // still capacity is 16.

// Now add the 17th character in the existing string buffer object.
sb.append("q");

System.out.println("After adding 17th character:");


System.out.println("Length = " +sb.length()); // length is 17
System.out.println("Capacity = " +sb.capacity()); // capacity is 34

// Add 17 characters to the existing object.


sb.append("abcdefghijklmnopq"); // 17 characters. So, total = 34 characters.

// Adding 35th character.


sb.append("r");

System.out.println("After adding 35th character:");


System.out.println("Length = " +sb.length()); // length is 35
System.out.println("Capacity = " +sb.capacity()); // Capacity is 70
}
}

Output:
Before adding any character:
Length = 0
Default initial capacity = 16

After adding 16 characters:


Length = 16
Capacity = 16

After adding 17th character:


Length = 17
Capacity = 34
After adding 35th character:
Length = 35
Capacity = 70

As you can observe, up to the 16th character, still capacity is 16 only. This is
because a new StringBuffer object has been created with a new capacity
when we added the 17th character.
When 34 characters are completed and added 35th character then a new
string buffer object with a bigger size is again created.
New capacity = ( 34 + 1 ) * 2 = 70.

Thus, StringBuffer has a growable nature. If the StringBuffer object reaches its
maximum capacity, a bigger StringBuffer object is created internally.

Second way:
We can create an object of StringBuffer class by using the new operator and
pass the string to the object. The general syntax to create StringBuffer object
with the specified string is given below:
StringBuffer sb = new StringBuffer(String s);

For example:
StringBuffer sb=new StringBuffer("Tech");
Capacity = sb.length() + 16 = 4 + 16 = 20

Here, we are passing string “Tech” in the StringBuffer object and “sb” is
pointing to that object i.e. the address of the StringBuffer object is stored in
reference variable sb.
Let’s take an example program based on it.
Program source code 2:
package stringBufferPrograms;
public class CapacityTest2 {
public static void main(String[ ] args)
{
StringBuffer sb = new StringBuffer("Tech");
int length = sb.length();
int capacity = sb.length() + 16;

System.out.println(length); // 4
System.out.println(capacity); // 20
}
}

Output:
4 20

Third way:
We can also create an empty StringBuffer object by declaring a size as an
argument for storing characters. The general syntax is as follows:
StringBuffer sb = new StringBuffer(int initialCapacity);

For example:
StringBuffer sb = new StringBuffer(30);

Here, an empty StringBuffer object has been created with a capacity for
storing 30 characters. But it is also possible to store more than 30 characters
in this object because StringBuffer is mutable and can expand dynamically in
the memory.
Suppose that we have a string “Hello” in string constant pool and it is fixed
and not changing frequently, we will need string class. Till now there is no
problem.
Now assume that we want to add content “Java” with string “Hello”. In this
case, compulsory a new object will be created with this change because a
string object is immutable. We are not allowed to change in the existing
object.
Now suppose the content is changing 10 times internally. This means that 10
times new objects will be created if the string will be used. In this situation,
performance will be gone to be down. Memory problems will also be created
in such a situation.
To overcome this kind of requirement, we should need or use a StringBuffer. If
we will use StringBuffer object and 10 times content is changing then still one
object will be created.
All the required changes will be performed in the existing object only. But if it
is string, for every small change, a new object will be created.
Due to which memory will waste and performance will be down. This is the
biggest advantage of StringBuffer technique in Java programming.

Key points:
1. In the case of String, for every small change, a new object will be created.
2. If StringBuffer is used, for all required changes, will perform in the existing
object only. No new object will be created in the memory by JVM.

Why do we need StringBuilder in Java?

StringBuffer and StringBuilder both represent a mutable sequence of


characters. We can change the content of StringBuffer and StringBuilder
without constructing a new object.
In Java, StringBuilder class is identical to StringBuffer class except one
important difference:
StringBuffer is thread-safe and StringBuilder is not thread-safe. Methods
provided by StringBuffer for modifying the buffer are synchronized, which
means that only one thread is allowed to access StringBuffer object at a time.
Most of the time, we do not require thread safety. In such as case, if we use
StringBuffer, the performance of the application will be down. Performance
wise, string buffer is not recommended to use.
This is the reason that StringBuilder class was added later in J2SE 5. The
main advantage of using StringBuilder is faster performance because multiple
threads have not to wait to access the same string builder object at a time.
That’s why, performance is relatively high.
Program source code :
public class StringBuilderDemo {
public static void main(String[] args)
{
StringBuilder sb = new StringBuilder("Every people love his country");
int length = sb.length();
System.out.println("Length: " + length);

int capacity = sb.capacity();


System.out.println("Capacity: " +capacity);
sb.ensureCapacity(50);
System.out.println("New capacity: " +sb.capacity());

sb.setLength(20);
System.out.println("After setLength, New StringBuilder: " +sb);
}
}

Output:
Length: 29
Capacity: 45
New capacity: 92
After setLength, New StringBuilder: Every people love hi

Program source code :


public class StringBuilderDemo {
public static void main(String[] args)
{
StringBuilder sb = new StringBuilder("Java Technology");
String str = sb.toString();
System.out.println("String form of StringBuilder: " +str);
String s1 = sb.substring(0, 9);
System.out.println("Substring: " +s1);
}
}

Output:
String form of StringBuilder: Java Technology
Substring: Java Tech

Advantage of using StringBuilder over StringBuffer

There are two main advantages of using StringBuilder class in Java over
StringBuffer. They are as:
1. StringBuilder is more efficient if it is accessed by just a single thread,
because no synchronization is required in this case.
2. It provides faster performance because thread is not synchronized.
3. Multiple threads can access the same string builder object at a time.

Disadvantage of using StringBuilder Class

Since methods present in StringBuilder class are not synchronized, therefore,


StringBuilder is not thread safe.

When to Use String, StringBuffer, or StringBuilder in


Java?

1. String is suitable to use when you do not want to modify the content in the
string object. String is an immutable class. Once created, its content cannot
be changed.
2. StringBuffer can be used when we want to perform any changes in the
content and need synchronization. It can be used when you are working in
multithreading environment.
3. StringBuilder can be used when you want to create a string within a single
thread. It will improve the execution time and performance.
StringBuilder is suitable to use when no thread-safety is needed.

You might also like