Mutable String in Java

There are two types of String in java mutable(Changeable) and immutable(Unchangeable). In this tutorial you will learn details explanation about mutable String in java with examples.

What is mutable String in java?

Mutable String means changing the String value over a time without creating new object. In simple words mutable String means String are changeable.

To create mutable string in java there are two built-in java classes.

  • StringBuffer()
  • StringBuilder()

Based on current situation we can used any classes for creating mutable string. To used in multi-threading environment and string should be thread-safe then StringBuilder class is better to used but in terms of performance StringBuffer is better as compared to StringBuilder.

Creation of Mutable String in java

To create mutable string in java we will use StringBuffer and StringBuilder class.

Example

Public static ExampleMutableString{
Public static void main(String[] args)
{
StringBuffer str1=new StringBuffer(“Kekmart”);
StringBuilder str2=new StringBuilder(“Cake Delivery”);
System.out.println(“str1 before print:”+ str1);
System.out.println(“str2 before print:”+ str2);

Str1.append(“.com”);
Str1.append(“ App”);

System.out.println(“str1 after print:”+ str1);
System.out.println(“str2 after print:”+ str2);
}
}

Output:

str1 before print:Kekmart
str2 before print:Cake Delivery
str1 after print:Kekmart.com
str1 after print:Cake Delivery App

In the above example code we had used StringBuffer and StringBuilder class to create mutable string in java.

JVM will change the value in existing of objects instead of creating new objects.

Was this article helpful?
YesNo

Leave a Comment