StringBuffer Methods in Java | Example Program

In addition to be inherited from the Object class methods, StringBuffer class also provide some useful methods in Java. They are as:

  • append()
  • capacity()
  • charAt()
  • delete()
  • ensureCapacity()
  • getChars()
  • indexOf()
  • insert()
  • length()
  • reverse() and many more.

So, let’s understand each StringBuffer class method one by one with example programs.

Append Methods of StringBuffer class in Java


1. append Method:

The append( ) method appends (or concatenates) the string representation of any other data type (e.g., boolean, int, float, long, String, Object, etc) to the end of the sequence of characters in the StringBuffer object.

This method has several overloaded versions that are as follows:

  • public StringBuffer append(boolean b)
  • public StringBuffer append(char c)
  • public StringBuffer append(char[ ] c )
  • public StringBuffer append(CharSequence cs)
  • public StringBuffer append(int i)
  • public StringBuffer append(float f)
  • public StringBuffer append(double d)
  • public StringBuffer append(long l)
  • public StringBuffer append(String s)
  • public StringBuffer append(StringBuffer sb1)
  • public StringBuffer append(Object o)
  • public StringBuffer append(char[ ]  c, int begin, int num)
  • public StringBuffer append(CharSequence cs, int begin, int num)

String.valueOf( ) is called for each parameter to get its string representation. The result is added to the end of the sequence of characters in the current StringBuffer object.

Let’s take a simple example program in which we will append

Program source code 1:

public class AppendDemo {
public static void main(String[] args)
{
  StringBuffer sb1 = new StringBuffer("Java");
  StringBuffer sb2 = new StringBuffer("Hello");
  StringBuffer sb3 = sb1.append(" Technology");
  StringBuffer sb4 = sb2.append(12345);
  System.out.println(sb3);
  System.out.println(sb4);
 } 
}
Output:
      Java Technology
      Hello12345

2. appendCodePoint(int codePoint): This method appends the string representation of the int argument codePoint to the sequence of characters in this StringBuffer and returns a reference to it.

The general syntax of this method is as below:

public StringBuffer appendCodePoint(int cp)

Let’s take a simple example program based on this method.

Program source code 2:

public class AppendCodePointDemo {
public static void main(String[] args)
{
  StringBuffer sb1 = new StringBuffer("Java");
  StringBuffer sb2 = sb1.append(" Programming");
  StringBuffer sb3 = sb2.appendCodePoint(66);
  System.out.println(sb3);
 } 
}
Output:
      Java ProgrammingB

Length and Capacity Methods of StringBuffer class


1. length():

The length() method returns the length of the current StringBuffer object. Length is the number of characters stored in buffer. The general syntax of length() method is as:

public int length()

2. capacity():

The capacity() method returns the current capacity of StringBuffer. The capacity is the total size of storage available for newly inserted characters, beyond which storage allocation will occur.


The general syntax of capacity() method is as:

public int capacity()

Let’s create a program in which we will find length and capacity of current StringBuffer object.

Program source code 3:

public class LengthCapDemo {
public static void main(String[] args)
{
  StringBuffer sb = new StringBuffer("Java Technology");
  System.out.println("Original string: " +sb);
  int lengthSB = sb.length();
  int capacitySB = sb.capacity();
  System.out.println("Length of StringBuffer: " +lengthSB);
  System.out.println("Capacity of StringBuffer: " +capacitySB);
 } 
}
Output:
      Original string: Java Technology
      Length of StringBuffer: 15
      Capacity of StringBuffer: 31

3. ensureCapacity():

This method ensures that the capacity is at least equal to the specified minimum capacity ‘mc’. The general syntax of this method is:

public void ensureCapacity(int mc) // here, mc is the minimum capacity.

a) If the current capacity is less than ‘mc’, a new internal array allocates with the greater capacity. The new capacity is larger of minimum capacity and sum of twice the old capacity plus 2.

b) If the minimum capacity ‘mc’ is non-positive, this method takes no action and simply returns.


4. setLength():

The setLength() method sets the length of the buffer within a StringBuffer object. Its general form is as follows:

public void setLength(int len) // Here, len specifies the length of buffer.

Let’s take an example program based on these methods.

Program source code 4:

public class LengthCapDemo {
public static void main(String[] args)
{
  StringBuffer sb = new StringBuffer("Hello World!");
  System.out.println("Original string: " +sb);
  int length = sb.length();
  int capacity = sb.capacity();
  System.out.println("Length: " +length);
  System.out.println("Capacity: " +capacity);
 
 sb.ensureCapacity(40);
 System.out.println("Now, capacity: " +sb.capacity());
 
 sb.setLength(15);
 System.out.println("Now, length: " +sb.length());
 } 
}
Output:
      Original string: Hello World!
      Length: 12
      Capacity: 28
      Now, capacity: 58
      Now, length: 15

In the preceding program, length of StringBuffer object is 12. Its capacity is 28. When the ensureCapacity() method is called with argument 40, the capacity will be 2 * 28 + 2 = 58.

Reading and Changing Characters in StringBuffer


The methods to read and change characters in a StringBuffer are as follows:

1. charAt():

This method obtains the value of a single character at the specified index. Its general form is as follows:

public int charAt(int i) // Here, 'i' specifies the index of character being obtained and must be non-negative.

2. setCharAt():

This method sets the value of a character at a specified index within StringBuffer object. The general form of this method is:

public void setCharAt(int i, char ch)

Here, index specifies the index of the character being set. It must be non-negative. char ch specifies the new value of that character.

Let’s take an example program based on these methods.

Program source code 5:

public class StringBufferDemo {
public static void main(String[] args)
{
   StringBuffer sb = new StringBuffer("Live with");
   System.out.println("Buffer before: " + sb);
   System.out.println("charAt(1) before: " + sb.charAt(1));
   sb.setCharAt(1, 'o');
   sb.setLength(4);
   System.out.println("Buffer after setting length: " + sb);
   System.out.println("charAt(1) after = " + sb.charAt(1));
 } 
}
Output:
      Buffer before: Live with
      charAt(1) before: i
      Buffer after setting length: Love
      charAt(1) after = o

3. codePointAt():

This method returns the character (Unicode code point) at the specified index. Its general form is given below:

public int codePointAt(int i) // Here, i specifies the index of the character being index.

4. codePointBefore():

This method returns the Unicode code-point before the specified “i”. The index ranges from 1 to length of this StringBuffer object. Its general syntax is given below:

public codePointBefore(int i)

5. codePointCount():

This method returns the number of Unicode code-points in the specified text range of StringBuffer object. Its general syntax is:

public int codePointCount(int begin, int end)

Let’s take an example program based on the above three methods.

Program source code 6:

public class StringBufferDemo {
public static void main(String[] args)
{
   StringBuffer sb = new StringBuffer("I love Java Programming");
   System.out.println("Original StringBuffer: " + sb);
   System.out.println("Character at index 7: " +sb.charAt(7));
 
   System.out.println("Unicode code point at index 7: " +sb.codePointAt(7));
   System.out.println("Unicode code point before index 7: " +sb.codePointBefore(7));
   System.out.println("Code points between indices 2 and 7: " +sb.codePointCount(2, 7));
 } 
}
Output:
       Original StringBuffer: I love Java Programming
       Character at index 7: J
       Unicode code point at index 7: 74
       Unicode code point before index 7: 32
       Code points between indices 2 and 7: 5

6. getChars():
This method copies a substring of a StringBuffer object into a character array specified by c. The general syntax is as follows:

public void getChars(int sourceStart, int sourceEnd, char[ ] c, int k)

Here, the first argument sourceStart specifies the index of the beginning of the substring.

The second argument sourceEnd specifies an index that is one last the end of the desired substring. It means that the substring contains characters from sourceStart through (sourceEnd – 1).

The third argument ‘c’ specifies the array of characters into which the coping is to be done. The fourth argument ‘k’ represents the index of character array at which the copying begins.

Let’s take an example program based on the getChars() method.

Program source code 7:

public class StringBufferDemo {
public static void main(String[] args)
{
  StringBuffer sb = new StringBuffer("Java Programming");
  System.out.println("Original StringBuffer: " + sb);
 
   char[ ] c = new char[9];
    sb.getChars(0, 8, c, 0);
   System.out.println("Contents of character array:");
   for(int i = 0; i < c.length; i++) {
	System.out.print(c[i] + " "); 
   }
 } 
}
Output:
      Original StringBuffer: Java Programming
      Contents of character array:
      J a v a   P r o 

How to Insert String into Java StringBuffer?


1. insert():

Java StringBuffer class provides insert() method that inserts a string representation of all simple data types plus String, Object, and CharSequence into invoking StringBuffer object.

The general syntax of the insert() method is as follows:

public StringBuffer insert(int index, data type)

Several overloaded version methods of insert() method are as follows:

  • StringBuffer insert(int index, boolean b)
  • StringBuffer insert(int index, char ch)
  • StringBuffer insert(int index, int i)
  • StringBuffer insert(int index, long l)
  • StringBuffer insert(int index, double d)
  • StringBuffer insert(int index, float f)
  • StringBuffer insert(int index, String str)
  • StringBuffer insert(int index, Object obj)
  • StringBuffer insert(int index, char[ ] c)
  • StringBuffer insert(int index, char[ ] c, int offset, int len)
  • StringBuffer insert(int index, CharSequence cs)
  • StringBuffer insert(int index, CharSequence, int start, int end)

Here, index indicates the index at which the string will be inserted into the calling StringBuffer object.

Like append( )method, this method also calls String.valueOf( ) to obtain the string representation of the value it is called with. This string value is then inserted into the calling StringBuffer object.

Let’s create a program in which we will insert string into StringBuffer object.

Program source code 8:

public class InsertDemo {
public static void main(String[] args)
{
   StringBuffer sb = new StringBuffer("I Java Programming!");
   System.out.println("Original StringBuffer: " + sb);
    sb.insert(2, "Like ");
   System.out.println("New StringBuffer: " +sb);
 } 
}
Output:
      Original StringBuffer: I Java Programming!
      New StringBuffer: I Like Java Programming!

How to Delete Characters within StringBuffer?


Java StringBuffer class provides two methods to delete characters within StringBuffer. They are as follows:

  • delete()
  • deleteCharAt()

1. delete():

The delete() method deletes a sequence of characters from the calling StringBuffer object. The general form of the delete() method is as below:

StringBuffer delete(int startIndex, int endIndex)

In the above syntax, startIndex defines the index of the first character to remove, and endIndex defines an index one past the last character to remove.

Thus, the substring deleted executes from startIndex to endIndex–1 and returns the resulting StringBuffer object.


2. deleteCharAt():

The deleteCharAt( ) method deletes the character at the specified index and then returns the resulting StringBuffer object. The general form is as follows:

StringBuffer deleteCharAt(int index)

The below program that demonstrates delete( ) and deleteCharAt( ) methods of StringBuffer class.

Program source code 9:

public class DeleteDemo {
public static void main(String[] args)
{
  StringBuffer sb = new StringBuffer("I love mango");
  System.out.println("Original StringBuffer: " + sb);
   sb.delete(0, 7);
  System.out.println("After delete: " + sb);
   sb.deleteCharAt(1);
  System.out.println("After deleteCharAt: " + sb);
 } 
}
Output:
       Original StringBuffer: I love mango
       After delete: mango
       After deleteCharAt: mngo

How to Replace Characters in StringBuffer?


1. replace():

StringBuffer class in Java provides a replace() method that replace one set of characters with another set inside a StringBuffer object. Its signature is given here:

StringBuffer replace(int startIndex, int endIndex, String s)

Here, startIndex and endIndex specifies the substring being replaced. Thus, the substring is replaced from startIndex to endIndex – 1. The replacement string is passed in String s. The resulting StringBuffer object is returned.

The following program demonstrates replace() method.

Program source code 10:

public class ReplaceDemo {
public static void main(String[] args)
{
   StringBuffer sb = new StringBuffer("I hate you");
   System.out.println("Original StringBuffer: " + sb);
    sb.replace(2, 6, "love");
   System.out.println("After replace: " +sb);
  } 
}
Output:
      Original StringBuffer: I hate you
      After replace: I love you

How to Search Indices of StringBuffer in Java?


The methods to search for indices of strings are as follows:

1. indexOf():

This method searches the invoking StringBuffer for the first occurrence of String s. It returns the index of the match, or –1 if no match is found. This method comes two flavors:

public indexOf(String s)
public indexOf(String s, int startIndex)

The second version is an overloaded version of indexOf() method. This overloaded method searches the invoking StringBuffer for the first occurrence of String s, starting at startIndex. It returns the index of the match, or –1 if no match is found.

2. lastIndexOf():

This method searches the calling StringBuffer object for the last occurrence of String s. It returns the index of the match, or –1 if no match is found. It comes into flavors:

public int lastIndexOf(String s)
public int lastIndexOf(String s, int startIndex)

The second overloaded version of lastIndexOf() method searches the calling StringBuffer for the last occurrence of String s, starting at startIndex. It returns the index of the match, or –1 if no match is found.

Let’s create a program where we will search indices of a string. Look at the following source code, as shown below:

Program source code 11:

public class SearchDemo {
public static void main(String[] args)
{
  StringBuffer sb = new StringBuffer("I am Java Programmer");
  System.out.println("Original StringBuffer: " + sb);
   int i;
    i = sb.indexOf("Java");
    System.out.println("First index: " + i);
    i = sb.lastIndexOf("Am");
    System.out.println("Last index: " + i);
  } 
}
Output:
      Original StringBuffer: I am Java Programmer
      First index: 5
      Last index: -1

How to Reverse Characters of StringBuffer in Java?


StirngBuffer class in Java provides a method reverse() that reverse the characters within a StringBuffer object. The reverse() method returns the reversed object on which it was called. Its general syntax is given as:

StringBuffer reverse( )

Let’s take an example program based on this method in which we will reverse the string.

Program source code 12:

public class ReverseDemo {
public static void main(String[] args)
{
  StringBuffer sb = new StringBuffer("ABCDEFGH");
  System.out.println("Original StringBuffer: " + sb);
    sb.reverse();
    System.out.println("New StringBuffer: " +sb);
 } 
}
Output:
      Original StringBuffer: ABCDEFGH
      New StringBuffer: HGFEDCBA

Getting Strings and Substrings


1. subSequence():

This method returns a substring of the calling string in the StringBuffer, starting at startIndex and stopping at stopIndex. Its general syntax is as follows:

public CharSequence subSequence(int startIndex, int stopIndex)

StringBuffer class implements CharSequence interface.

2. substring( ):

This method is used to obtain a portion of a StringBuffer by calling substring( ). It comes in the following two forms:

String substring(int startIndex)
String substring(int startIndex, int endIndex)

The first form of method returns the substring of StringBuffer that begins at startIndex and runs to the end of the invoking StringBuffer object.

The second form of method returns the substring of StringBuffer that begins at startIndex and runs through endIndex – 1. Look at the example program based on this method.

Program source code 13:

public class SubstringDemo {
public static void main(String[] args)
{
  StringBuffer sb = new StringBuffer("PQRSTUVWXYZ");
  System.out.println("Original StringBuffer: " + sb);
  String s1 = sb.substring(3);
 
  System.out.println("Substring: " +s1);
   String s2 = s1.substring(2, 5);
   System.out.println("New Substring: " +s2);
 } 
}
Output:
      Original StringBuffer: PQRSTUVWXYZ
      Substring: STUVWXYZ
      New Substring: UVW

3. toString():

This method returns a string representing data in the sequence of characters in the StringBuffer object. In other simple words, this method converts StringBuffer object into a string. Look at the example program based on this method.

Program source code 14:

public class ToStringDemo {
public static void main(String[] args)
{
 StringBuffer sb = new StringBuffer("PQRSTUVWXYZ");
 System.out.println("Original StringBuffer: " + sb);
 String s = sb.substring(2); 
 String s2 = s.toString();
 System.out.println("String representation of StringBuffer: " +s2);
 } 
}
Output:
     Original StringBuffer: PQRSTUVWXYZ
     String representation of StringBuffer: RSTUVWXYZ

Other StringBuffer Class Methods in Java


1. trimToSize():

This method is used to trim the capacity of StringBuffer. Assume the number of characters in the character sequence of StringBuffer is small, and the buffer is bigger than necessity. In a such case, this method can be used to resize the buffer. Its general form is as:

public void trimToSize()

2. getClass():

This method returns the runtime class of this StringBuffer. The general syntax of this method is:

public final Class getClass()

3. hashCode():

This method is used to get hashCode value of this StringBuffer. Its general form is:

public int hashCode()

Let’s take a simple program based on these methods.

Program source code 15:

public class tringBufferDemo {
public static void main(String[] args)
{
  StringBuffer sb = new StringBuffer("PQRST");
  System.out.println("Original StrinBuffer: " +sb);
  System.out.println("Original capacity: " +sb.capacity());
   
   sb.trimToSize();
   System.out.println("New capacity: " +sb.capacity());
   System.out.println("Runtime class: " +sb.getClass());
   System.out.println("Hashcode value: " +sb.hashCode());
  }
}
Output:
      Original StrinBuffer: PQRST
      Original capacity: 21
      New capacity: 5
      Runtime class: class java.lang.StringBuffer
      Hashcode value: 31168322

Hope that this tutorial has covered almost all the important methods of StringBuffer class in Java. I hope that you will have understood and practiced all programs based on Java StringBuffer class methods.

Thanks for reading!!!
Next ⇒ Java StringBuilder Class⇐ Prev Next ⇒