๐ŸŽ“ A1Learner
๐Ÿ”
0 of 40 lessons completed

Java StringBuilder

A StringBuilder is a growing buffer for building text. Joining text with plus in a loop builds a new string each round.

Append chains build a sentence

Each append adds at the end. One buffer holds the whole sentence.

public class Main {
  public static void main(String[] args) {
    StringBuilder builder = new StringBuilder();
    builder.append("Hello").append(" ").append("world");
    System.out.println(builder.toString());
  }
}

Insert slips text into the middle

Position 6 sits before the word world. The new word lands there.

public class Main {
  public static void main(String[] args) {
    StringBuilder builder = new StringBuilder("Hello world");
    builder.insert(6, "brave ");
    System.out.println(builder.toString());
  }
}

Delete cuts a range

Delete removes positions 6 up to, but not including, 12. The sentence returns to its short form.

public class Main {
  public static void main(String[] args) {
    StringBuilder builder = new StringBuilder("Hello brave world");
    builder.delete(6, 12);
    System.out.println(builder.toString());
  }
}

Reverse flips the buffer

Reverse turns the whole buffer around. The last letter becomes the first.

public class Main {
  public static void main(String[] args) {
    StringBuilder builder = new StringBuilder("live");
    builder.reverse();
    System.out.println(builder.toString());
  }
}

Example

public class Main {
  public static void main(String[] args) {
    StringBuilder builder = new StringBuilder("Hello");
    builder.append(" world");
    builder.insert(6, "brave ");
    String text = builder.toString();
    System.out.println(text);
    System.out.println(new StringBuilder(text).reverse().toString());
  }
}

Key points

  • A StringBuilder grows one buffer instead of building a new string each round.
  • Append adds text at the end, and append calls chain.
  • Insert slips text into the middle at a position.
  • Delete cuts a range from the buffer.
  • Reverse flips the whole buffer.
  • ToString hands back a plain String.

In this example, a builder grows a greeting, inserts a word, and then prints both the built text and its reversal.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

A builder holds "Hello world". What does delete(6, 11) leave?