What Is the Difference Between String Stringbuffer and Stringbuilder in Java

Stay updated on What Is the Difference Between String Stringbuffer and Stringbuilder in Java. Discover expert viewpoints in full detail.

StringBuffer class is used to make String objects mutable. Therefore, those objects can be modified. StringBuffer defines four constructors. StringBuffer(), StringBuffer(int size), StringBuffer(String str), StringBuffer (charSequence [] ch)

Refer the code below,

StringBuffer s1= new StringBuffer(“Hello”);

s1.append(“World”);

System.out.println(s1);

In statement 1, s1 is referring to the “Hello” object in a heap. The object is mutable because it is created using StringBuffer. In statement 2, “World” is appended to the same “Hello” String object.

String objects created with StringBuffer class can save memory. StringBuffer provides thread safety because two threads cannot access the same method in the StringBuffer class simultaneously. Thread safety decrease StringBuffer performance. StringBuffer class contain methods such as append(), insert(), reverse(), replace().

Related Stories