0

Difference Between String & String Builder

28th Nov 2016, 7:21 PM
Aamir Shaikh
3 Antworten
+ 6
StringBuilder is much more dynamic each time you append to a string builder using the append() method, you add the input to the EXISTING object with a String object, you mostly use the += operator, which simply create NEW combined string in the memory, resulting in an obsolote reference which will be picked by the garbage collector (eventually) so following few additiona to compare will look like this: StringBuilder st = new StringBuilder(); st.append("This "); st.append("is "); st.append("my "); st.append("string!"); String str = ""; str += "This "; str += "is "; str += "my "; str += "string!"; in the memory the String would look like this "" "This " "This is " "This is my " "This is my string!" whereas the StringBuilder will retain the same starting memory each append, adding only the address for the append operation. this might not look like much, but do this for millions of strings over a short span of time and eventually your memory is slowly getting clogged.
28th Nov 2016, 7:30 PM
Burey
Burey - avatar
+ 2
Well, the most important difference between String and StringBuffer/StringBuilder in java is that String object is immutable whereas StringBuffer/StringBuilderobjects are mutable. By immutable, we mean that the value stored in the String object cannot be changed. ... Next, you want to append “Guest” to the same String.
28th Nov 2016, 7:49 PM
Abdelaziz Abubaker
Abdelaziz Abubaker - avatar
+ 1
String String is immutable, Immutable means if you create string object then you cannot modify it and It always create new object of string type in memory. Example string strMyValue = "Hello Visitor"; // create a new string instance instead of changing the old one strMyValue += "How Are"; strMyValue += "You ??"; Stringbuilder StringBuilder is mutable, means if create string builder object then you can perform any operation like insert, replace or append without creating new instance for every time.it will update string at one place in memory doesnt create new space in memory. Example StringBuilder sbMyValue = new StringBuilder(""); sbMyValue.Append("Hello Visitor"); sbMyValue.Append("How Are You ??"); string strMyValue = sbMyValue.ToString();
30th Nov 2016, 2:13 PM
Akwin Lopez
Akwin Lopez - avatar