0
0
Javaprogramming~15 mins

StringBuilder and StringBuffer in Java

Choose your learning style8 modes available
menu_bookIntroduction

StringBuilder and StringBuffer help you change text without making new copies every time. This saves memory and makes your program faster.

When you need to build or change a text many times, like adding words one by one.
When you want to join many small pieces of text into one big text.
When you want to change text inside a loop without slowing down your program.
When you want to safely change text in programs that run many parts at the same time (use StringBuffer).
regular_expressionSyntax
Java
StringBuilder sb = new StringBuilder();
sb.append("Hello");
String result = sb.toString();

StringBuilder is faster but not safe for programs running many parts at once.

StringBuffer is slower but safe for programs running many parts at once.

emoji_objectsExamples
line_end_arrow_notchThis adds two pieces of text and prints "Hi there".
Java
StringBuilder sb = new StringBuilder();
sb.append("Hi");
sb.append(" there");
System.out.println(sb.toString());
line_end_arrow_notchThis starts with "Start" and adds more text safely for multi-thread use.
Java
StringBuffer sbf = new StringBuffer("Start");
sbf.append(" and continue");
System.out.println(sbf.toString());
line_end_arrow_notchThis builds a list of numbers separated by commas.
Java
StringBuilder sb = new StringBuilder();
sb.append("Count: ");
for(int i=1; i<=3; i++) {
    sb.append(i).append(", ");
}
System.out.println(sb.toString());
code_blocksSample Program

This program shows how to add text pieces using StringBuilder and StringBuffer, then prints the results.

Java
public class Main {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder();
        sb.append("Hello");
        sb.append(", ");
        sb.append("World!");
        System.out.println(sb.toString());

        StringBuffer sbf = new StringBuffer("Java");
        sbf.append(" is fun");
        System.out.println(sbf.toString());
    }
}
OutputSuccess
emoji_objectsImportant Notes
line_end_arrow_notch

Use StringBuilder when you do not need to worry about multiple parts running at the same time.

line_end_arrow_notch

Use StringBuffer if your program changes text from many parts at once to avoid errors.

line_end_arrow_notch

Both classes help avoid creating many new strings, which saves memory and time.

list_alt_checkSummary

StringBuilder and StringBuffer let you build and change text efficiently.

StringBuilder is faster but not thread-safe; StringBuffer is thread-safe but slower.

Use them when you need to change text many times instead of using normal strings.