Difference of String, StringBuilder and StringBuffer in Java?
String
1)String value are stored in dynamic memory (managed heap) and variables of type string keep a reference to an object in heap.
2)The character sequence stored in string variable of class are immutable i.e never changing.
3)The value is assigned once to string variable, altering the value of string will be saved to new location in dynamic memory and will store reference of new string.
StringBuilder
The character sequence stored in StringBuilder variable are mutable i.e they can be changed. The changed string is saved in the same memory location where previous string was stored.
StringBuffer
StringBuffer are same as StringBuilder with only one difference that StringBuffer are thread safe i.e multiple threads can use it without any problem. StringBuilder is faster and is preferred over StringBuffer for single threaded program but if thread safety is required, then StringBuffer is used.
Java program to demonstrate difference between String, StringBuilder and StringBuffer
class Demo
{
public static void concat1(String s1) //Concat function for String
{
s1 = s1 + "program";
}
public static void concat2(StringBuilder s2) //Concat function for StringBuilder
{
s2.append("First java");
}
public static void concat3(StringBuffer s3) //Concat function for StringBuffer
{
s3.append("First java");
}
public static void main(String[] args)
{
String s1 = "First";
concat1(s1); // s1 is not changed
System.out.println("String: " + s1);
StringBuilder s2 = new StringBuilder("program");
concat2(s2); // s2 is changed
System.out.println("StringBuilder: " + s2);
StringBuffer s3 = new StringBuffer("program");
concat3(s3); // s3 is changed
System.out.println("StringBuffer: " + s3);
}
}
Output:
String: First
StringBuilder: First java program
StringBuffer: First java program
0 Comment(s)