What is a String Builder in java | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

What is a String Builder in java

7th Feb 2017, 3:03 PM
Prakhar Agarwal
Prakhar Agarwal - avatar
7 Answers
+ 3
Pretty sure the answer has something to do with multi threading.. jk. it's a dynamic array that can produce equivalent strings on demand.
7th Feb 2017, 3:40 PM
Leon
Leon - avatar
+ 3
StringBuilder is Java class that is usually used as substitution for String class when you need to do a lot of concatenation, for example: String a = ""; for(int i = 0; i < 100; i++){ a += "a" } So, since String class is IMMUTABLE and you cannot change its value, what is really happening is that in every iteration compiler makes completely NEW OBJECT of String class and assigns a value of the old string and new value to it concatenated. StringBuilder is mutable, so there is no making new objects when assigning new values while iterating. So, you should use StringBuilder when you are certain that value of your string CHANGES A LOT. You can always transfer your StringBuilder object to string with simple .toString() method when finished.
7th Feb 2017, 4:02 PM
Ladislav Milunović
Ladislav Milunović - avatar
+ 3
@Prakhar Agarwal Good question. From java docs (StringBuffer): As of release JDK 5, this class has been supplemented with an equivalent class designed for use by a single thread, StringBuilder. The StringBuilder class should generally be used in preference to this one, as it supports all of the same operations but it is faster, as it performs no synchronization. So, you should use StringBuilder over StringBuffer if you don't do multithreading.
7th Feb 2017, 5:14 PM
Ladislav Milunović
Ladislav Milunović - avatar
+ 3
string: immutable stringBuffer:mutable nd Unsynchronized stringBuildr:Mutable and Synchronized (such that use in multithreaded environment)
8th Feb 2017, 5:50 AM
Shreyance Gupta
Shreyance Gupta - avatar
0
Thnx Leon But can u send me any example of it
7th Feb 2017, 3:44 PM
Prakhar Agarwal
Prakhar Agarwal - avatar
0
Thnx for ur help
7th Feb 2017, 3:49 PM
Prakhar Agarwal
Prakhar Agarwal - avatar
0
Thnx Milunovic but is it same. as string buffer
7th Feb 2017, 4:17 PM
Prakhar Agarwal
Prakhar Agarwal - avatar