Difference between String, String Builder, and String Buffer? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Difference between String, String Builder, and String Buffer?

Can anyone explain the exact difference between these.

15th Dec 2019, 5:45 AM
Ujjwal Sinha
Ujjwal Sinha - avatar
1 Answer
+ 4
String is immutable in Java, whenever we do String manipulation like concatenation, substring it generates a new String and discards the older String for garbage collection, these heavy operation generated garbage in heap area so java provides String buffer and StringBuilder that provides creation of mutable strings. StringBuffer is thread safe means all methods of this class are synchronized multiple threads can not call the methods of this class on a same object, Like if one thread has called a method of this class on a object then other threads have to wait for the complete execution of that method and after execution one of these threads can acquire the same object and can call other method. But StringBuilder is not thread safe means it's methods are not synchronized so multiple threads can call any method simultaneously on same object. So you should use StringBuffer when resources are not in shared mode means you don't want that multiple threads manipulate your string at same time
15th Dec 2019, 6:10 AM
Vijay Shyam Sharma
Vijay Shyam Sharma - avatar