0
0
Javaprogramming~15 mins

String vs StringBuilder in Java

Choose your learning style8 modes available
menu_bookIntroduction

Strings hold text that does not change often. StringBuilder helps build or change text efficiently without making many copies.

When you have a fixed message or name that won't change.
When you need to add or change text many times, like building a sentence word by word.
When you want your program to run faster while changing text.
When you want to save memory by not creating many copies of text.
When you are working with user input that changes often.
regular_expressionSyntax
Java
String text = "Hello";
StringBuilder builder = new StringBuilder("Hello");

String is simple and easy to use for fixed text.

StringBuilder is better for changing text many times.

emoji_objectsExamples
line_end_arrow_notchThis creates a new String each time you add text, which can be slow if done many times.
Java
String greeting = "Hi";
greeting = greeting + " there!";
line_end_arrow_notchThis changes the same StringBuilder object without making new copies, so it is faster.
Java
StringBuilder builder = new StringBuilder("Hi");
builder.append(" there!");
line_end_arrow_notchUsing StringBuilder to build a greeting step by step.
Java
String name = "Alice";
StringBuilder sb = new StringBuilder();
sb.append("Hello, ").append(name).append("!");
code_blocksSample Program

This program shows how String creates a new text when adding, while StringBuilder changes the same object.

Java
public class Main {
    public static void main(String[] args) {
        String text = "Start";
        text = text + " and continue";
        System.out.println("Using String: " + text);

        StringBuilder builder = new StringBuilder("Start");
        builder.append(" and continue");
        System.out.println("Using StringBuilder: " + builder.toString());
    }
}
OutputSuccess
emoji_objectsImportant Notes
line_end_arrow_notch

String objects are immutable, meaning they cannot change once created.

line_end_arrow_notch

StringBuilder is mutable, so it can change without making new objects.

line_end_arrow_notch

Use StringBuilder when you need to change text many times for better speed and memory use.

list_alt_checkSummary

String is good for fixed text that does not change.

StringBuilder is better for building or changing text many times.

Choosing the right one helps your program run faster and use less memory.