StringBuilder in Java

  • StringBuilder is the same as the StringBuffer class
  • The StringBuilder class is not synchronized and hence in a single threaded environment, the overhead is less than using a StringBuffer.
  • A StringBuilder has a capacity (the number of characters it can hold) and a length (the number of characters it is currently holding)
  • If the capacity is exceeded, the StringBuilder is copied to a new location with more room
  • StringBuilder is a reimplementation of StringBuffer
    • The API (collection of methods) is the same
    • StringBuffers are threadsafe, but StringBuilders are more efficient
  • StringBuilders are used to implement String concatenation
    • Whenever you say String s = "ab" + "cd", Java creates a StringBuffer containing the characters a and b, appends the characters c and d to it, and converts the result back to a String
    • As you might guess, this isn’t terribly efficient, but it’s fine if you don’t overdo it
StringBuilder() : Constructs a StringBuilder with a capacity of 16 characters
StringBuilder(int capacity) :Constructs a StringBuilder with the requested capacity
StringBuilder(String str): Constructs a StringBuilder containing the String str