We will find answer for following questions

  • What is StringBuffer
  • Available Constructors
  • Commonly used methods
StringBuffer
  • Java StringBuffer class is used to create mutable (modifiable) string.
  • The StringBuffer class in java is same as String class except it is mutable i.e. it can be changed.
  • The Java StringBuffer class is same as StringBuilder class except that this one is synchronized.
  • So its thread safe and can be used if Object are shared among multiple thread.
  • If sb refers to an instance of a StringBuffer, then sb.append(x) has the same effect as sb.insert(sb.length(), x).
Constructors
// creates an empty stringBuffer with the initial capacity of 16.
StringBuffer str = new StringBuffer();

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

// creates an empty stringBuffer with the specified capacity as length.
StringBuffer str = new StringBuffer(40);
Common 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 StringBuffer();
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.