StringBuffer class in Java

StringBuffer in Java is used to create modifiable strings i.e. it doesn’t have a fixed length like the String class in Java. The StringBuffer class has growable and writable character sequences.  It is thread safe i.e. multiple threads cannot simultaneously access the same method.

Let us see how to create a string using StringBuffer:

StringBuffer vs. String

The String class has fixed length i.e. cannot be changed, whereas StringBuffer is growable and creates modifiable (mutable) strings. Let us now see the differences:


StringBuffer class Constructors

The constructors of StringBuffer are displayed below:

StringBuffer class Constructors

StringBuffer class Methods

The methods of StringBuffer displayed below with description:

StringBuffer Methods

For complete reference of the StringBuffer methods, refer the Oracle Java StringBuffer docs.

StringBuffer Examples

Following are some of the examples of StringBuffer:

Append the string representation

The append() method in Java appends the string representation. Here append(char ch) appends the string representation of the char argument to this sequence:

The output is as follows:

Find the current capacity

To fetch the current capacity, the capacity() method is used in Java:

The output is as follows:

Reverse the value of the StringBuffer object

To reverse the value of the StringBuffer object, the reverse() method in Java is to be used:

The output is as follows:

break continue statements in Java
Java Program to get the default value of primitive data types
Studyopedia Editorial Staff
[email protected]

We work to create programming tutorials for all.

No Comments

Post A Comment

Discover more from Studyopedia

Subscribe now to keep reading and get access to the full archive.

Continue reading