StringBuffer java

java.lang.StringBuffer class represents a string or a sequence of characters.
A StringBuffer is similar to a string, but its content can be modified or changed after it is created.
Thus, it is called a mutable class.

StringBuffer is a thread-safe class meaning that its instances are safe to use in a multi-threaded environment.
This is because all of the methods which modify its state are synchronized.

When multiple operations need to be performed on a string, such as adding a string to another or substring, then StringBuffer should be used instead of a string.
After all the operations are done, it can be converted to a string using toString() method.

StringBuffer constructors
A StringBuffer can be created using its constructor. It has following three overloaded constructors

1. StringBuffer()
This constructor takes no argument and creates a StringBuffer with empty value and an initial capacity of 16 characters.

2. StringBuffer(int)
This constructor takes an integer argument and creates a StringBuffer with empty value and an initial capacity of characters equal to the supplied argument.

3. StringBuffer(String)
This constructor takes a string argument and creates a StringBuffer with value initialized to the supplied argument and length equal to 16 + length of string.

4. StringBuffer(CharSequence)
Same as above except that it accepts a CharSequence as argument. Note that CharSequence is an interface and String  and StringBuffer classes implement it.

StringBuffer java example
Below is an example of StringBuffer class which creates its object using its constructors and prints their contents.

// no-arg constructor
StringBuffer sb1 = new StringBuffer();
// int argument constructor
StringBuffer sb2 = new StringBuffer(25);
// string argument constructor
StringBuffer sb3 = new StringBuffer("Abc");
System.out.println("Length="+sb1.length() +
                   ",Content="+sb1.toString());
System.out.println("Length="+sb2.length() +
                   ",Content="+sb2.toString());
System.out.println("Length="+sb3.length() +
                   ",Content="+sb3.toString());

We can get the number of characters stored in a StringBuffer with its length() method.
Output is

Length=0,Content=
Length=0,Content=
Length=3,Content=Abc

Note that the initial capacity of first and second StringBuffer instances are 16 and 25 respectively. Still their lengths are 0.
This is because the contents of both these objects are empty.

StringBuffer java methods
Below are the important methods of StringBuffer class with explanations and their examples.

1. append(String)
append() method accepts a string argument and adds this string to the end of StringBuffer on which it is called. Example,

StringBuffer sb = new StringBuffer("Abc");
System.out.println("Before append: " + sb.toString());
sb.append("Def");
System.out.println("After append: " + sb.toString());

This prints

Before append: Abc
After append: AbcDef

Note that append() modifies the original StringBuffer. It is not required to re-assign to variable.

There are many overloaded versions of append() which accept and character, character array, integer, long, float, double, boolean type as arguments.
All of these methods internally convert the argument value to string and then append it to StringBuffer. If the argument is null, then it appends “null” (null converted to string).
2. charAt(int)
Returns the character at given index.
It throws a java.lang.StringIndexOutOfBoundsException if the index is out of range of string. Example,

StringBuffer sb = new StringBuffer("Abc"); 
char c = sb.charAt(1); // b
sb.charAt(5); StringIndexOutOfBoundsException

3. delete(int, int)
Removes the substring between the supplied integer arguments. Substring begins at first index and ends at second index – 1. Example,

StringBuffer sb = new StringBuffer("Abcdefg"); 
StringBuffer s = sb.delete(2, 5); 
System.out.println(s.toString()); // Abfg

Note that delete() returns the sameStringBuffer on which it is called. This means that it modifies the original StringBuffer.
4. deleteCharAt(int)
It deletes the character at given integer index and returns the modified StringBuffer on which it is invoked. Example,

StringBuffer sb = new StringBuffer("Abcde");
StringBuffer s = sb.deleteCharAt(2);
System.out.println(s.toString()); // Abde

Throws StringIndexOutOfBoundsException if the index is negative or greater than the length of string.

5. indexOf(String)
Returns the index of the first occurrence of the argument string in StringBuffer. Example,

StringBuffer sb3 = new StringBuffer("Abcdefg");
int index = sb3.indexOf("cde");
System.out.println(index); // 2

Note that the start index of matching string is returned. If there is no matching string, then -1 is returned.
6. indexOf(String, int)
Returns the index of the first occurrence of the argument string in StringBufferafter the index specified by second argument.
That is, it searches for the string after the second argument index position. Example,

StringBuffer sb3 = new StringBuffer("Abcdefg"); 
int index = sb3.indexOf("cde", 3); 
System.out.println(index); // -1
index = sb3.indexOf("cde", 1); 
System.out.println(index); // 2

Returns -1 if the string is not present after the supplied index.
6. insert(int, String)
Inserts the string argument starting from the index position of the first argument. Remaining characters of StringBuffer are shifted to the right. Example,

StringBuffer sb3 = new StringBuffer("Abcd"); 
StringBuffer insert = sb3.insert(1, "xyz"); 
System.out.println(insert.toString()); // Axyzbcd

There are many overloaded versions of insert() which accept and character, character array, integer, long, float, double, boolean type as arguments.
All of these methods internally convert the argument value to string and then append it to StringBuffer. If the argument is null, then it appends “null” (null converted to string).
7. lastIndexOf(String)
Returns the last index of the argument string in this StringBuffer object. That is, if the string occurs 2 times, then it will return the index of its second occurrence. Example,

StringBuffer sb3 = new StringBuffer("Abcdefcde");
int index = sb3.lastIndexOf("cde");
System.out.println(index); // 6

Note that the start index of matching string is returned. If there is no matching string, then -1 is returned.
8. lastIndexOf(String, int)
Returns the first index of the argument string in this StringBuffer object searching backwards from the index specified by the second argument.
That is, it searches for the string from right to left(in reverse direction) starting from the second argument index position. Example,

StringBuffer sb3 = new StringBuffer("Abcdefcde");
int index = sb3.lastIndexOf("cd",1);
System.out.println(index); // -1
index = sb3.lastIndexOf("cd",5);
System.out.println(index); // 2
index = sb3.lastIndexOf("cd",sb3.length());
System.out.println(index); // 6
9. length()
Returns the number of characters in StringBuffer. Example,

StringBuffer sb = new StringBuffer("Abc"); 
int length = sb.length(); // 3

10. replace(int, int, String)
Replaces the substring between the supplied integer arguments with the supplied string argument. Substring begins at first index and ends at second index – 1. Example,

StringBuffer sb3 = new StringBuffer("Abcdefg");
StringBuffer replaced = sb3.replace(2, 5,"xyz");
System.out.println(replaced.toString()); // Abxyzfg

If the length of replaced string is greater than the range of indexes given, then space is created for the string. That is, complete string is accommodated and the characters to the right are shifted further. Example,

StringBuffer sb3 = new StringBuffer("Abcdefg"); 
StringBuffer replaced = sb3.replace(2, 5,"vwxyz"); 
System.out.println(replaced.toString()); // Abvwxyzfg

11. reverse()
Reverses the contents of this StringBuffer object. Reverse means that last character becomes the first, second last becomes the second character and so on. Example,

StringBuffer sb3 = new StringBuffer("Abcde");
sb3.reverse();
System.out.println(sb3.toString()); // edcbA

12. substring(int)
Returns a string with characters starting with the given index till the end of string.
Note that characters in StringBuffer are indexed with the first character at index 0 and so on. Example,

StringBuffer sb = new StringBuffer("Abcde"); 
String s = sb.substring(2);
System.out.println(s); // cde

substring() throws StringIndexOutOfBoundsException if the index argument is invalid.
13. substring(int, int)
Returns a substring between the supplied integer arguments. Substring begins at first index and ends at second index – 1. Example,

StringBuffer sb3 = new StringBuffer("Abcdefg");
String substring = sb3.substring(2, 5);
System.out.println(substring); // cde

substring() throws StringIndexOutOfBoundsException  if start or end index are negative, greater than length of string or start index is greater than end index.
Difference between String and StringBuffer
Following are some important differences between String and StringBuffer

StringStringBuffer
String is immutable.
This means that any operation on a string object creates a new string object.
StringBuffer is mutable.
Any operation on a StringBuffer is performed on the same object.
No new object is created.
Due to above reason, String consumes more memory.StringBuffer consumes lesser memory as compared to String.
Since string creates a new object upon every operation such as addition of two strings, it is slower.Concatenation is performed on same StringBuffer object.
New objects are not created, hence it is faster.
String uses a String constant pool to store values.StringBuffer uses heap memory.
String overrides equals() method. So, you can compare the contents of two string objects.StringBuffer does not override equals() method, it uses equals() method from Object class, which compares references only.
String overrides hashCode() method.StringBuffer does not override hashCode() method.

That is all on StringBuffer class in java, its usage, benefits and its important methods with examples.

0
Liked the article ? Spread the word...