StringBuffer in Java

In this tutorial, we will learn about StringBuffer in Java.

StringBuffer in java is a thread-safe, mutable class. A Stringbuffer is same as String, the difference is that we can modify it. The String represents fixed-length, immutable character sequences. StringBuffer represents growable and writeable character sequences. We can append characters and substrings at the end or insert in the middle of StringBuffer using some methods in it. StringBuffer will automatically grow to make room for such additions and often has more characters pre-allocated than are actually needed, to allow room for growth.

StringBuffer Constructors:

The StringBuffer class has following four constructors.

Some of the methods in StringBuffer class are:

apepend(), length( ), capacity( ), replace(), reverse(), ensureCapacity() etc. The length of a StringBuffer can be found by the length( ) method, while the total allocated capacity can be found by the capacity( ) method.

Key points about StringBuffer:

1) StringBuffer is same as String, the difference is that it can be modified.
2) StringBuffer is thread-safe, it can be used in multithreaded environment.

Example:

Output:

Other Tutorials:

Java String trim() method

Related posts

Leave a Comment