Java StringBuffer

StringBuffer class

Java StringBuffer

As We already know that String is immutable, once created it’s content can never be modified. But in some cases, we need to manipulate string contents and we don’t want JVM to create new String objects on each modification.

In this tutorial, we will discuss how we can solve this problem with StringBuffer. How we can create mutable string in java. We will discuss important methods of StringBuffer and some interesting examples.


StringBuffer class





Before we proceed, let’s first get know StringBuffer.

StringBuffer Class

StringBuffer class is same as String class in java but different in nature.  StringBuffer class in java is used to create mutable String objects which can be modified at any time. StringBuffer is mutable so we can modify original String object and JVM will not create any new object after modification.

StringBuffer can create Thread-Safe, mutable String object which can be modified at any time. StringBuffer objects are thread safe.

(We will discuss about multi threading and thread safety concept later but for now, Thread safety is a feature of java in which only one source can access the object at one time. If other source need the object at the same time, it will have to wait until first source is completing it’s task).

Some Important things about StringBuffer class

  1. StringBuffer is used to create mutable string objects.
  2. StringBuffer class is thread safe, only one thread can access object at a time.
  3. Methods of StringBuffer class are synchronized.
  4. You can perform append, reverse, replace and other operation on same StringBuffer object.


StringBuffer constructor

Like String class, StringBuffer also have some overloaded constructors which are used to initialize string. Let’s see them below.

StringBuffer()
It creates an empty String with the initial capacity of 16 characters.
StringBuffer(CharSequence seq)
You can create String with the character sequence specified by CharSequence interface.
StringBuffer(int capacity)
StringBuffer creates empty string with initial capacity of 16 characters but you can specify your own.
StringBuffer(String str)
Creates a StringBuffer object and initialize it String object.


StringBuffer class methods

You can manipulate StringBuffer object without creating any new object at run time. StringBuffer provides different objects to modify contents of StringBuffer object. Let’s discuss them one by one.

StringBuffer append(String str)
This method will append the given string at the end of the existing StringBuffer object.
int capacity()
Returns the current capacity.
char charAt(int index)
Returns the char value in this sequence at the specified index.
StringBuffer delete(int start, int end)
You can delete the characters from StringBuffer object at specified position.
StringBuffer deleteCharAt(int index)
Removes the char at the specified position in this sequence.
StringBuffer insert(int offset, String str)
This method will insert given string into the existing StringBuffer object at the given location which is the offset.
StringBuffer replace(int start, int end, String str)
This method will replace the given string at specified position in StringBuffer object and no new object will be created after replace.
StringBuffer reverse()
Method returns the reversed characters of StringBuffer object.
void setCharAt(int index, char ch)
You can set character at specified position.
String substring(int start)
Returns sub string from the specified position in StringBuffer object.
String substring(int start, int end)
You can also specify the position from where you want sub string.
String toString()
Returns a string representing the data in this sequence.
void trimToSize()
Attempts to reduce storage used for the character sequence.



Now let’s create some interesting examples on StringBuffer class.

1. An example on StringBuffer replace method

public class StringBufferReplace {
 
 public static void main(String[] args) {
 
 StringBuffer strB = new StringBuffer("Welcome to StringBuffer example.");
 System.out.println("Original Text : " + strB);
 
 strB.replace(0,6,"Hello");
 System.out.println("Replaced Text : " + strB);
 
 }
}

2. An example on StringBuffer reverse method

public class StringBufferReplace {
 
 public static void main(String[] args) {
 
 StringBuffer strB = new StringBuffer("Welcome to StringBuffer example.");
 System.out.println("Original Text : " + strB);
 
 strB.reverse();
 System.out.println("Reversed Text : " + strB);
 
 }
}

3. StringBuffer delete example

public class StringBufferDelete {
 
 public static void main(String[] args) {

 StringBuffer sb1 = new StringBuffer("Welcome to the example of StringBuffer.");
 sb1.delete(0,6);
 System.out.println(sb1);
 
 StringBuffer sb2 = new StringBuffer("Hello");
 System.out.println(sb2);
 sb2.delete(0, sb2.length());
 System.out.println(sb2);

 StringBuffer sb3 = new StringBuffer("Welcome");
 sb3.deleteCharAt(0);
 System.out.println(sb3);
 } 
}


It’s time for some exercise

  1. Write a java program to replace input string in a given string buffer.
  2. Write a java program to find how many times an input string is found in a given string.
  3. Write a java program to reverse a string only from specified position. Example, “Hello world” reverse(0, 2) output “leHlo world”.
  4. Write a java program to remove all spaces from a given string. ” hello to java” to “hellotojava”.
  5. Write a java program to convert given character to upper case in string buffer object. “hello world”  given character is ‘l’ then “heLLo worLd”.
  6. Write a java program to find the frequency of a given character. How many times a particular character appears in string.
  7. Write a program to remove all duplicate characters from a given string.
  8. Write a program to check if the given string and it’s reverse version are same. Like “nitin” and it’s reverse version “nitin” both are same.

Leave a Reply

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