xxxxxxxxxx
It is mutable char sequence and it is not
thread safe.
xxxxxxxxxx
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello "); //init
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
}
xxxxxxxxxx
StringBuilder in Java represents a mutable sequence of characters.
Since the String Class in Java creates an immutable sequence of characters,
the StringBuilder class provides an alternative to String Class, as it creates
a mutable sequence of characters
xxxxxxxxxx
// Create a new StringBuilder object
StringBuilder sb = new StringBuilder();
// Append characters to the StringBuilder
sb.append("Hello");
sb.append(" ");
sb.append("World!");
// Insert characters at a specific index
sb.insert(5, "Awesome ");
// Replace characters at a specific range
sb.replace(0, 5, "Hi");
// Delete characters at a specific range
sb.delete(2, 5);
// Convert the StringBuilder to a String
String result = sb.toString();
System.out.println(result); // Output: "Hillo World!"
xxxxxxxxxx
//new StringBuilder()
using System.Text;
StringBuilder bldr = new StringBuilder();
var startTime = DateTime.Now;
for (int i = 0; i< 1_000_000; i++)
{
bldr.Append(i.ToString());
}
var stopTime = DateTime.Now;
Console.WriteLine($"Started:{startTime} Stopped:{stopTime}");
Console.ReadKey();
//Started:1/13/2023 11:22:10 AM Stopped:1/13/2023 11:22:10 AM
xxxxxxxxxx
Java StringBuilder class is used to create
mutable (modifiable) string. The Java
StringBuilder class is same as StringBuffer
class except that it is non-synchronized.
StringBuilder()
creates an empty string Builder with the initial capacity of 16.
StringBuilder(String str)
creates a string Builder with the specified string.
StringBuilder(int length)
creates an empty string Builder with the specified capacity as length.
xxxxxxxxxx
public final class StringBuilder
extends Object
implements Serializable, CharSequence