We will find answer for following questions

  • What is StringBuilder
  • Available Constructors
  • Commonly used methods
StringBuilder
  • Java StringBuilder class is used to create mutable (modifiable) string.
  • The Java StringBuilder class is same as StringBuffer class except that it is non-synchronized.
  • So its not thread safe and can’t be used if Objects are shared among multiple thread.
  • It is available since JDK 1.5.
  • If sb refers to an instance of a StringBuilder, then sb.append(x) has the same effect as sb.insert(sb.length(), x)
Constructors
// creates an empty string Builder with the initial capacity of 16.
StringBuilder str = new StringBuilder();

// creates a string Builder with the specified string.
StringBuilder str = new StringBuilder("Hello World");

// creates an empty string Builder with the specified capacity as length.
StringBuilder str = new StringBuilder(40);
Commonly used Methods
// used to append the specified string with this string. 
// The append() method is overloaded like append(char),
// append(boolean), append(int), append(float), append(double) etc.
str.append(" from India");

// reverse the order of characters
str.reverse();

// Convert to String
String data = str.toString();

// return the length of the string
str.length();

// clears object
str.setLength(0);
str = new StringBuilder();

 

Categories: JAVA

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.