Using StringBuilder in Java

In Java, strings have an immutable nature, implying that they cannot be altered once they're formed. This characteristic can sometimes cause performance issues, especially during frequent string modifications, because a new String object is generated with every change. To mitigate this, Java introduced the StringBuilder class under the java.lang package. This class enables more efficient string manipulations without the overhead of creating a fresh object after every tweak. Methods like append(), insert(), delete(), and reverse() are prevalent in StringBuilder, making it a go-to choice when numerous string operations are required, primarily within looping structures. In this Java StringBuilder Example, we did some manipulations using StringBuilder. Click Execute to run the Java StringBuilder Example online and see the result.
Using StringBuilder in Java Execute
public class StringBuilderDemo {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("Hello");

        sb.append(" World");

        sb.insert(5, ",");

        StringBuilder reversedSb = new StringBuilder(sb).reverse();

        System.out.println("Original StringBuilder: " + sb);
        System.out.println("Reversed StringBuilder: " + reversedSb);
Updated: Viewed: 39 times