Java - StringBuilder and StringBuffer

Introduction

StringBuilder and StringBuffer are companion classes for the String class.

You can change the content of StringBuilder and StringBuffer without creating a new object.

StringBuffer is thread-safe and StringBuilder is not thread-safe.

Both classes have the same methods, except that all methods in StringBuffer are synchronized.

The StringBuilder class contains four constructors:

StringBuilder()
StringBuilder(CharSequence seq)
StringBuilder(int capacity)
StringBuilder(String str)

The following are some examples of creating StringBuilder objects:

Create an empty StringBuilder with a default initial capacity of 16 characters

StringBuilder sb1 = new StringBuilder();

Create a StringBuilder from of a string

StringBuilder sb2 = new StringBuilder("Here is the content");

Create an empty StringBuilder with 200 characters as the initial capacity

StringBuilder sb3 = new StringBuilder(200);

Demo

public class Main {
  public static void main(String[] args) {
    // Create an empty StringNuffer
    StringBuilder sb = new StringBuilder();
    printDetails(sb);// w  ww .  j a  va2s  .co m

    // Append "blessings"
    sb.append("blessings");
    printDetails(sb);

    // Insert "abc " in the beginning
    sb.insert(0, "abc ");
    printDetails(sb);

    // Delete the first o
    sb.deleteCharAt(1);
    printDetails(sb);

    // Append " def"
    sb.append(" def");
    printDetails(sb);

    // Set the length to 3
    sb.setLength(3);
    printDetails(sb);

    // Reverse the content
    sb.reverse();
    printDetails(sb);
  }

  public static void printDetails(StringBuilder sb) {
    System.out.println("Content: \"" + sb + "\"");
    System.out.println("Length: " + sb.length());
    System.out.println("Capacity: " + sb.capacity());

    // Print an empty line to separate results
    System.out.println();
  }
}

Related Topics

Exercise