JAVA BASICS IN DETAIL

Java StringBuilder

StringBuilder is a mutable character sequence. It is useful for repeatedly appending or editing text because each change does not require creating a new String object.

The difference between String and StringBuilder

String object is immutable. Adding text creates a new String object. StringBuilder can change its contents within the same object.

String and StringBuilder comparison
PropertyStringStringBuilder
ContentsImmutableMutable
Simple textVery suitableOften unnecessary
Many changesMay create many intermediate objectsChanges one accumulated buffer
Common useConstant or rarely changed textBuilding text in a loop

Your first StringBuilder

StringBuilder tekstas = new StringBuilder();

tekstas.append("Labas");
tekstas.append(" ");
tekstas.append("Rūta");
tekstas.append("!");

System.out.println(tekstas);
Console output

Labas Rūta!

  1. new StringBuilder() creates an empty text-building object.
  2. append() adds a new value at the end of its contents.
  3. Add spaces yourself: Java does not insert them automatically.
  4. println() can display the accumulated contents directly.

The same object changes several times

StringBuilder sarasas = new StringBuilder("Duona");

sarasas.append(", pienas");
System.out.println(sarasas);

sarasas.append(", obuoliai");
System.out.println(sarasas);
Console output

Duona, pienas
Duona, pienas, obuoliai

Both append() calls append to the same sarasas object. This is the key difference from String, where each concatenation produces a new string object.

Inserting, replacing and deleting text

StringBuilder tekstas = new StringBuilder("Kava skani");

tekstas.insert(5, "labai ");
System.out.println(tekstas);

tekstas.replace(0, 4, "Arbata");
System.out.println(tekstas);

tekstas.delete(7, 13);
System.out.println(tekstas);
Console output

Kava labai skani
Arbata labai skani
Arbata skani

  • insert(5, "labai ") inserts text at index 5.
  • replace(0, 4, "Arbata") replaces characters from index 0 to 4, exclusive.
  • delete(7, 13) removes the word and space in the specified range.

Method chaining and toString()

String vardas = "Mantas";
int taskai = 18;

String zinute = new StringBuilder()
    .append(vardas)
    .append(" surinko ")
    .append(taskai)
    .append(" taškų.")
    .toString();

System.out.println(zinute);
Console output

Mantas surinko 18 taškų.

Because append() returns the same StringBuilder, so you can call the next method immediately. Once the text is complete, toString() converts it to a regular String.

StringBuilder in a loop

A loop is one of the most common places where StringBuilder is particularly useful:

String[] produktai = {"duona", "pienas", "obuoliai"};
StringBuilder sarasas = new StringBuilder();

for (int i = 0; i < produktai.length; i++) {
    if (i > 0) {
        sarasas.append(", ");
    }
    sarasas.append(produktai[i]);
}

System.out.println(sarasas);
Console output

duona, pienas, obuoliai

  1. The loop visits every product in turn.
  2. From the second product onward, a comma and space are added before the name.
  3. Each product is appended to the same StringBuilder.
  4. When the loop ends, the entire list is printed once.

reverse() and length()

StringBuilder zodis = new StringBuilder("labas");

zodis.reverse();

System.out.println(zodis);
System.out.println(zodis.length());
Console output

sabal
5

reverse() reverses the character order in the same object. length() returns the current character count.

When should you choose StringBuilder?

  • when building text in a loop;
  • when repeatedly appending, inserting, replacing or shortening text;
  • when forming one result from many separate values.
Simple concatenation does not need it.

The line String zinute = "Labas, " + vardas; is clear and appropriate. StringBuilder is most beneficial when operations repeat many times.

StringBuilder is not synchronized and is not designed for safely modifying the same object from multiple threads. For that special case, there is StringBuffer, but ordinary single-threaded code usually uses StringBuilder.