Most of us are familiar with the String immutability in java. If someone
doesn’t know about the String immutability please refer the link below:
Due to this immutability strings are not recommended for the
projects where we need to update the string data frequently because it will
consume a lot of memory as it creates the objects every time a new string value
is created in string pool memory so java has given StringBuilder and
StringBuffer to overcome this immutability constraint. They are pretty much
similar to the String except that they are mutable. They have their own methods
for data manipulation. To understand this more clearly please refer the below
example:
Example Code:
public class demoString {
public static void main(String s[])
{
String st = new String
("JAVA");
st.concat(" is great");
System.out.println("The result of
String : "+st);//this will only print JAVA
StringBuffer sbf = new StringBuffer
("JAVA");
sbf.append(" is great");
System.out.println("The result of
StringBuffer : "+sbf);//this will print JAVA is great
StringBuilder sb = new StringBuilder
("JAVA");
sb.append(" is great");
System.out.println("The result of
StringBuilder : "+sb);//this will print JAVA is great
}}
Output:
The result of String : JAVA
The result of StringBuffer :
JAVA is great
The result of StringBuilder
: JAVA is great
As
in above example we can see that string does not concated the value “is great” to
“JAVA “because of its immutability property but StringBuilder and StringBuffer
do that because they both are mutable.
The
StringBuilder and StringBuffer in java are almost same but the main difference
is that StringBuffer is synchronized (which means it is thread safe and hence
you can use it when you implement threads for your methods) whereas
StringBuilder is not synchronized (which implies it isn’t thread safe).
Note: StringBuilder was introduced
in Java 1.5 (so if you happen to use versions 1.4 or below you’ll have to use
StringBuffer)