Week 16 — What is StringBuilder class in Java, and what are it's possible uses

Question of the Week #16
What is StringBuilder class in Java, and what are it's possible uses
14 Replies
Eric McIntyre
Eric McIntyre2y ago
StringBuilder is a mutable class. Unlike String class that holds a collection of chars, the String class is immutable. When we combine two strings (or append), it creates a new String class, discarding the old one.
The StringBuilder class allows us to use the append method which allows us to combine a collection of chars with another. The StringBuilder will modify the original object themselves. This will result in less garbage left over to collect by the garbage collector.
Submission from Awe#9789
Eric McIntyre
Eric McIntyre2y ago
StringBuilder is a symptom of Java being an inefficient language. Appending to a string like this is very costly:
String str = "Good morning";
str += ", how is your day?";
String str = "Good morning";
str += ", how is your day?";
This is because strings are immutable, meaning their state cannot be changed. What actually happens behind the scenes is that there exists a pointer called str that is pointing to a string "Good morning". But now, str points to "Good morning, how is your day?". Since "Good morning" is no longer referenced to by a pointer, it gets eaten by the garbage collector.
Eric McIntyre
Eric McIntyre2y ago
What is your alternative? StringBuilder was designed to fix this problem. Their approach is to create a buffer for appending characters. The existence of this buffer makes it much more efficient to append values to strings, and not every addition to a string requires a garbage collector anymore. This is how you would use the StringBuilder:
StringBuilder str = new StringBuilder();
str.append("Good morning");
str.append(", how is your day?");
StringBuilder str = new StringBuilder();
str.append("Good morning");
str.append(", how is your day?");
Submission from amicharski#7113
Eric McIntyre
Eric McIntyre2y ago
With the string builder you can create long strings or set together a text. You can either do it like this:
String text = "This is the start of the ";
if(textNumber == 5){
text += "final text!";
} else {
text += textNumber + " text";
}
String text = "This is the start of the ";
if(textNumber == 5){
text += "final text!";
} else {
text += textNumber + " text";
}
However, with the stringbuilder it will look better then this version. The stringbuilder is even better, if it is a long and complex text with many additions like the example above. Here is the example, how it would be done with the stringbuilder:
StringBuilder text = new StringBuilder("This is the start of the ");
if(textNumber == 5){
text.append("final");
} else {
text.append(textNumber);
}
text.append(" text!");
StringBuilder text = new StringBuilder("This is the start of the ");
if(textNumber == 5){
text.append("final");
} else {
text.append(textNumber);
}
text.append(" text!");
Submission from Giotsche#5027
Eric McIntyre
Eric McIntyre2y ago
StringBuilder is an alternative to the String Class that allows for the use of mutable character sequences. It’s possible uses are to allow for cases when mutable strings are needed. It prevents having to have the garbage collector invoked when creating new strings (seen in using the String Class). StringBuilder is fast in operation, but is not thread safe. StringBuilder also has some additional methods, such as reverse and the ability to set the capacity of a character sequence.
Submission from MilaDog#1234
Eric McIntyre
Eric McIntyre2y ago
A Stringbuilder class in java allows to periodically build a String from several other strings.
public static void main(String[] args){
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("Hell");
stringBuilder.append("o ");
stringBuilder.append("World!");
System.out.println(stringBuilder.toString());
}
public static void main(String[] args){
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("Hell");
stringBuilder.append("o ");
stringBuilder.append("World!");
System.out.println(stringBuilder.toString());
}
The output will be the String
Hello World
Hello World
Submission from Ignitrum#0176
Eric McIntyre
Eric McIntyre2y ago
its very smilar to StringBuffer but with diffrent that StringBuffer methods are not synchronized in these two class we can give a string to its parameters and change it example:
StringBuilder builder = new StringBuilder("20");
builder.append("23");
String numeric = builder.toString();
System.err.println(numeric);
StringBuilder builder = new StringBuilder("20");
builder.append("23");
String numeric = builder.toString();
System.err.println(numeric);
so i changed the value of this class so this is a mutable class like StringBuffer with diffrent the StringBuffer class is threadsafe
Eric McIntyre
Eric McIntyre2y ago
cause its contains synchronized methods for example when im going to append things in StringBuilder its not synchronized and when im usin in it another threads they can started with no limit
Submission from melon_#4695
Eric McIntyre
Eric McIntyre2y ago
StringBuilder is a java class which represents a mutable sequence of characters. It also provides an alternative to String Class by making a mutable sequence of characters. It the possibly recommended that this class be used in preference to StringBuffer as it will be faster under most implementations. Example of StringBuilder:- public class StringBuilderExample { public static void main(String[] args) { StringBuilder sb = new StringBuilder(); sb.append("Hello"); sb.append(" "); sb.append("world!"); System.out.println(sb.toString()); // Output: "Hello world!" sb.insert(6, "beautiful "); System.out.println(sb.toString()); // Output: "Hello beautiful world!" sb.reverse(); System.out.println(sb.toString()); // Output: "!dlrow lufituaeb olleH" } }
Submission from moaliyou#4310
Eric McIntyre
Eric McIntyre2y ago
The StringBuilder class contains utilities to manipulate strings without having to work with several String objects. A very easy use case for them would be as a drop-in for repeated string concatenation (string += anotherString), since most of the StringBuilder methods are Intrinsic candidates, making them faster and more efficient than their pure-java counterpart (since a human wrote assembly replacements for them):
StringBuilder sb = new StringBuilder();
for(int i = 0;i<100;i++) {
sb.append("Iteration ").append(i).append("\n");
}
String full = sb.substring(0, sb.length()-1); // cut off \n
System.out.println(full);
// Alternatively:
System.out.print(sb); // .toString() is implicit
StringBuilder sb = new StringBuilder();
for(int i = 0;i<100;i++) {
sb.append("Iteration ").append(i).append("\n");
}
String full = sb.substring(0, sb.length()-1); // cut off \n
System.out.println(full);
// Alternatively:
System.out.print(sb); // .toString() is implicit
There are also some useful text manipulation methods, like insert, delete, etc:
StringBuilder sb = new StringBuilder("This server is great!"); // you can also specify an existing string as initial state
System.out.println(sb); // "This server is great!"
sb.replace(0, 11, "Java"); // -> Java is great!
System.out.println(sb); // -"-
sb.delete(1, 4); // J is great!
sb.insert(1, "VM"); // JVM is great!
sb.insert(0, "The "); // The JVM is great!
System.out.println(sb); // -"-
StringBuilder sb = new StringBuilder("This server is great!"); // you can also specify an existing string as initial state
System.out.println(sb); // "This server is great!"
sb.replace(0, 11, "Java"); // -> Java is great!
System.out.println(sb); // -"-
sb.delete(1, 4); // J is great!
sb.insert(1, "VM"); // JVM is great!
sb.insert(0, "The "); // The JVM is great!
System.out.println(sb); // -"-
Submission from 0x150#9699
Eric McIntyre
Eric McIntyre2y ago
StringBuilder is a class for holding a string value; We use that when we want to make some operation on our value; Why? because if we for example add to our value "Hello " value "World", system doesn't add these 2 strings, instead that it deletes an old string and creates a new string. That makes our application slower; We can add, delete, compare etc our String by StringBuilder and do not slow down out app.
Submission from Karolus#1973
Eric McIntyre
Eric McIntyre2y ago
StringBuilder is a class that allows programmers to concatenate strings. You do this by creating a new StringBuilder() object and calling append(String) on the object. "That sounds like string += s!", you might be saying. That's very true, but it solves a very important issue: Strings need to be created too. You see, you use StringBuilder in cases where you're working with pre-existing String objects so the program doesn't need to create new "old string plus new string" objects every single time it concatenates a new one. Let's say you have the following array of Strings that were created somewhere else - String[] strings = getStringsFromOtherPlace() - and you need to add all of these strings together to make a new string of all of them combined. One way you could do this is:
String out = "";
for (String s : strings) {
out += s;
}
String out = "";
for (String s : strings) {
out += s;
}
The problem is that each time this is done, out becomes a brand new object (e.g. out + s = "asdf" + "xyz" = "asdfxyz") that needs to be created uniquely every single time a new string is added to it. Why do we need to do this when each s already exists somwhere else in memory? We can save memory by using StringBuilder instead:
StringBuilder stringbuilder = new StringBuilder();
for (String s : strings) {
stringbuilder.append(s);
}
String output = stringbuilder.toString();
StringBuilder stringbuilder = new StringBuilder();
for (String s : strings) {
stringbuilder.append(s);
}
String output = stringbuilder.toString();
When StringBuilder#append is called, it simply stores a reference to that string in a list to that when StringBuilder#toString is called, instead of creating each individual "string1 + string2" string along the way, it only creates one new String object with the combined size of each individual string that was appended. An interesting thing is that both examples may, in practice, be exactly the same, because the compiler can replace out += s with the StringBuilder version instead when it's compiled. Still, if you're doing something more complicated, it can be worth it to use StringBuilder manually.
⭐ Submission from Haiku#1184
Eric McIntyre
Eric McIntyre2y ago
StringBuilder is a class allowing to creating and manipulate Strings. For example, it is possible to incrementally create a String as follows:
StringBuilder sb = new StringBuilder();//creates a new StringBuilder representing the empty string
sb.append("Hello");//append the string "Hello"
sb.append(' ');//append a single character ' '
sb.append("World");
sb.append('\n');//append a single character (newline)
sb.append(1337);//append the string representation of the int 1337
String result=sb.toString();//"Hello World" in first line and "1337" in second line
StringBuilder sb = new StringBuilder();//creates a new StringBuilder representing the empty string
sb.append("Hello");//append the string "Hello"
sb.append(' ');//append a single character ' '
sb.append("World");
sb.append('\n');//append a single character (newline)
sb.append(1337);//append the string representation of the int 1337
String result=sb.toString();//"Hello World" in first line and "1337" in second line
Before Java 8, string concatenation used StringBuilder. For example, "a"+someInt was equivalent (same bytecode) with new StringBuilder().append("a").append(someInt).toString(). In Java 9, the new bytecode instruction invokedynamic was used instead as the JVM/JIT was able to better optimize that. However, it is still better (in most cases) to use StringBuilder when incrementally building a String using a loop as string concatenation always creates a new String.
//slow
String s = "";
for(int i=0;i<100;i++){
s += "\n"+i;//creates a new String each iteration, copying all the data
}
//slow
String s = "";
for(int i=0;i<100;i++){
s += "\n"+i;//creates a new String each iteration, copying all the data
}
//more performant
StringBuilder sb = new StringBuilder();
for(int i=0;i<100;i++){
sb.append('\n').append(i);//this just adds it to the existing StringBuilder without copying all the data each iteration
}
//more performant
StringBuilder sb = new StringBuilder();
for(int i=0;i<100;i++){
sb.append('\n').append(i);//this just adds it to the existing StringBuilder without copying all the data each iteration
}
Aside from appending, StringBuilder provides methods for other operations. For example, the method reverse() reverses the whole String and insert can be used for inserting something at a given position. Changing the length using the method setLength() is also possible. If the length is decreased, excess characters (at the end) are removed from the StringBuilder. If the new length is greater than the old length, it will add (\0) at the end as often as necessary.
StringBuilder sb = new StringBuilder("dlroW");
sb.reverse();//World
sb.insert(0,"Hello");//HelloWorld
sb.insert(5,' ');//Hello World
sb.setLength(5);//Hello
sb.setLength(10);//Hello\0\0\0\0\0
sb.deleteCharAt(4);//Hell\0\0\0\0\0
sb.setCharAt(4,'o');//Hello\0\0\0\0
sb.replace(2,4,"r");//Hero\0\0\0\0
int length=sb.length();//8
StringBuilder sb = new StringBuilder("dlroW");
sb.reverse();//World
sb.insert(0,"Hello");//HelloWorld
sb.insert(5,' ');//Hello World
sb.setLength(5);//Hello
sb.setLength(10);//Hello\0\0\0\0\0
sb.deleteCharAt(4);//Hell\0\0\0\0\0
sb.setCharAt(4,'o');//Hello\0\0\0\0
sb.replace(2,4,"r");//Hero\0\0\0\0
int length=sb.length();//8
Eric McIntyre
Eric McIntyre2y ago
Most mutating (modifying) methods of StringBuilder return the current StringBuilder instance. This allows for chaining:
new StringBuilder()
.append("dlroW")
.reverse()//World
.insert(0,"Hello")//HelloWorld
.insert(5,' ');//Hello World
new StringBuilder()
.append("dlroW")
.reverse()//World
.insert(0,"Hello")//HelloWorld
.insert(5,' ');//Hello World
⭐ Submission from dan1st#7327
Want results from more Discord servers?
Add your server