Mutable Strings in Java

Mutable Strings in Java

Mutable Strings:

As we discussed earlier Java Strings are Immutable, once assigned the value to the Strings those values can’t be changed. and to access the character level data we need to use some specialized methods like charAt() methods., Now we are going to discuss about How to make Strings mutable.

There are two predefined classes Which are ..

  1. String Buffer
  2. String Builder

String Buffer

StringBuffer is a predefined class in the Java , using this class we can able to extend the data in the String variable using the method called append(), See the Example below for better understanding.


In the above Example we have created the String s1 with the name “Become” using the class StringBuffer. and in the next lines we are appending the words “a” and “Geek” to the s1 string.

The initial capacity of the String Buffer is 16., when the length is equal to the capacity, then in order to increase the capacity the following formula applied. Current Capacity * 2 +2

String Builder

StringBuilder is similar to StringBuffer, StringBuilder is not synchronized which means it is not Thread safe, we use StringBuilder class where the Thread safety is not an issue. StringBuilder is faster than StringBuffer. The methods which were available in the StringBuffer will also available in the StringBuider. For better understanding of StringBuilder see the following example.

In the above example we just replaced StringBuffer with StringBuilder and you can observe output of this program Become a Geek.

Leave a Reply

Your email address will not be published. Required fields are marked *