StringBuffer Class Methods in Java

In this article, we will learn all StringBuffer Class Methods with examples. The class diagram shows a list of StringBuffer class methods that we are going learn in this article.

StringBuffer APIs/Methods

The diagram shows a list of methods offered by StringBuffer Class
append() methods

It has several overloaded versions. Here are all its forms:
  1. StringBuffer append(boolean b) - Appends the string representation of the boolean argument to the sequence.
  2. StringBuffer append(char c) - Appends the string representation of the char argument to this sequence.
  3. StringBuffer append(char[] str) - Appends the string representation of the char array argument to this sequence.
  4. StringBuffer append(char[] str, int offset, int len) - Appends the string representation of a subarray of the char array argument to this sequence.
  5. StringBuffer append(CharSequence s) - Appends the specified CharSequence to this sequence.
  6. StringBuffer append(CharSequence s, int start, int end) - Appends a subsequence of the specified CharSequence to this sequence.
  7. StringBuffer append(double d) - Appends the string representation of the double argument to this sequence.
  8. StringBuffer append(float f) - Appends the string representation of the float argument to this sequence.
  9. StringBuffer append(int i) - Appends the string representation of the int argument to this sequence.
  10. StringBuffer append(long lng) - Appends the string representation of the long argument to this sequence.
  11. StringBuffer append(Object obj) - Appends the string representation of the Object argument.
  12. StringBuffer append(String str) - Appends the specified string to this character sequence.
  13. StringBuffer append(StringBuffer sb) - Appends the specified StringBuffer to this sequence.
  14. StringBuffer appendCodePoint(int codePoint) - Appends the string representation of the codePoint argument to this sequence.
Let's demonstrate each append() method with examples.
Example: This program demonstrates the usage of above 14 append methods.
public class AppendExample {
 public static void main(String[] args) {
  // 14 append overloaded methods

  // Append String
  StringBuffer buffer;
  buffer = new StringBuffer().append("guides");
  System.out.println("Append String : " + buffer);

  // Append char
  buffer = new StringBuffer().append('c');
  System.out.println("Append char : " + buffer);

  // Append Object
  buffer = new StringBuffer().append(new Object().getClass());
  System.out.println("Append Object : " + buffer);

  // Append chars
  char[] chars = { 'j', 'a', 'v', 'a' };
  buffer = new StringBuffer().append(chars);
  System.out.println("Append chars : " + buffer);

  // Append charSequence
  CharSequence charSequence = new String("charSequence");
  buffer = new StringBuffer().append(charSequence);
  System.out.println("Append charSequence : " + buffer);

  // Append Double
  buffer = new StringBuffer().append(10.0d);
  System.out.println("Append Double : " + buffer);

  // Append Float
  buffer = new StringBuffer().append(10.5f);
  System.out.println("Append Float : " + buffer);

  // Append int
  buffer = new StringBuffer().append(100);
  System.out.println("Append int : " + buffer);

  // Append Boolean
  buffer = new StringBuffer().append(true);
  System.out.println("Append Boolean : " + buffer);

  // Append Long
  buffer = new StringBuffer().append(1000);
  System.out.println("Append Long : " + buffer);

  // Append stringbuffer
  buffer = new StringBuffer().append(new StringBuffer("stringbuffer"));
  System.out.println("Append stringbuffer : " + buffer);

  // Appends the string representation of a subarray of the char array
  // argument to this sequence.
  buffer = new StringBuffer().append(chars, 1, 3);
  System.out.println("Appends the string representation of a "
    + " subarray of the char array argument to this sequence.  : " + buffer);

  // Appends a subsequence of the specified CharSequence to this sequence
  buffer = new StringBuffer().append("javaguides", 0, 9);
  System.out.println("Appends a subsequence of the specified " 
  + " CharSequence to this sequence. : " + buffer);

  // Appends the string representation of the codePoint argument to this
  // sequence.
  buffer = new StringBuffer().appendCodePoint(5);
  System.out.println(
    "Appends the string representation of the "
  + " codePoint argument to this sequence.  : " + buffer);
 }
}
Output:
Append String : guides
Append char : c
Append Object : class java.lang.Object
Append chars : java
Append charSequence : charSequence
Append Double : 10.0
Append Float : 10.5
Append int : 100
Append Boolean : true
Append Long : 1000
Append stringbuffer : stringbuffer
Appends the string representation of a  subarray of the char array argument to this sequence.  : ava
Appends a subsequence of the specified  CharSequence to this sequence. : javaguide
Appends the string representation of the  codePoint argument to this sequence.  : 

capacity()

This method returns the current capacity. The capacity is the amount of storage available for newly inserted characters, beyond which an allocation will occur.
Example: This simple program demonstrates the usage of capacity() method.
public class CapacityExample {
 public static void main(String[] args) {
  StringBuffer builder = new StringBuffer("javaguides");
  int capacity = builder.capacity();
  
  // inital capacity
  System.out.println(new StringBuffer().capacity());
  
  // intial capacity 16 + number of characters in string
  System.out.println("Capacity of the string :: " + capacity);
 }
}
Output:
16
Capacity of the string :: 26

charAt(int index)

Returns the char value at the specified index. An index ranges from zero to length() - 1. The first char value of the sequence is at index zero, the next at index one, and so on, as for array indexing.
To extract a single character from a String, you can refer directly to an individual character via the charAt( ) method.
This method throws IndexOutOfBoundsException - if an index is negative or greater than or equal to length().
Example 1: Returns the char value at the specified index of this string. The first char value is at index 0.
StringBuffer buffer = new StringBuffer("Welcome to string handling guide");
char ch1 = buffer.charAt(0);
char ch2 = buffer.charAt(5);
char ch3 = buffer.charAt(11);
char ch4 = buffer.charAt(20);
System.out.println("Character at 0 index is: " + ch1);
System.out.println("Character at 5th index is: " + ch2);
System.out.println("Character at 11th index is: " + ch3);
System.out.println("Character at 20th index is: " + ch4);
Output:
Character at 0 index is: W
Character at 5th index is: m
Character at 11th index is: s
Character at 20th index is: n
Example 2: Example to throws IndexOutOfBoundsException - if index is negative or greater than or equal to length().
public static void charAtExample2() {
StringBuffer builder = new StringBuffer("Java Guides");
char ch1 = builder.charAt(builder.length());
System.out.println("character :: " + ch1);
Output:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 11
 at java.lang.StringBuffer.charAt(StringBuffer.java:202)
 at com.javaguides.stringbuffer.methods.ChatAtExample.charAtExample2(ChatAtExample.java:26)
 at com.javaguides.stringbuffer.methods.ChatAtExample.main(ChatAtExample.java:6)
Example 3: Example how to get a first and last character of the string
public static void charAtExample3() {
StringBuffer buffer = new StringBuffer("Java Guides");
int strLength = buffer.length() - 1;
// Fetching first character
System.out.println("Character at 0 index is: " + buffer.charAt(0));
// The last Character is present at the string length-1 index
System.out.println("Character at last index is: " + buffer.charAt(strLength));
Output:
Character at 0 index is: J
Character at last index is: s

codePointAt(int index)

This method returns the character (Unicode code point) at the specified index. The index refers to char values (Unicode code units) and ranges from 0 to length()- 1.
This method throws the IndexOutOfBoundsException - if the index argument is negative or not less than the length of this string.
Example:
public class CodePointAtExample {
 public static void main(String[] args) {
  StringBuffer buffer = new StringBuffer("javaguides");
  int unicode = buffer.codePointAt(0);
  System.out.println("the character (Unicode code point) at the specified index is :: " + unicode);
 }
}
Output;
the character (Unicode code point) at the specified index is :: 106

codePointBefore(int index)

This method returns the character (Unicode code point) before the specified index. The index refers to char values (Unicode code units) and ranges from 1 to length.
This method throws the IndexOutOfBoundsException - if the index argument is negative or not less than the length of this string.
Example:
public class CodePointBeforeExample {
 public static void main(String[] args) {
  StringBuffer buffer = new StringBuffer("javaguides");
  int unicode = buffer.codePointBefore(1);
  System.out.println("the character (Unicode code point)"
    + "  at the before specified index is :: " + unicode);
 }
}
Output:
the character (Unicode code point) at the before specified index is :: 106

codePointCount(int beginIndex, int endIndex)

This method returns the number of Unicode code points in the specified text range of this String. The text range begins at the specified beginIndex and extends to the char at index endIndex - 1.
This method throws IndexOutOfBoundsException - if the beginIndex is negative, or endIndex is larger than the length of this String, or beginIndex is larger than endIndex.
Example:
public class CodePointCountExample {
 public static void main(String[] args) {
  StringBuffer buffer = new StringBuffer("javaguides");
  System.out.println("length of the string :: " + buffer.length());
  int unicode = buffer.codePointCount(0, buffer.length());
  System.out.println("the character (Unicode code point) "
    + " at the specified index is :: " + unicode);
 }
}
Output:
length of the string :: 10
the character (Unicode code point)  at the specified index is :: 10

delete(int start, int end)

This method removes the characters in a substring of this sequence. The substring begins at the specified start and extends to the character at index end - 1 or to the end of the sequence if no such character exists. If start is equal to end, no changes are made.
Example: Example to delete substring 'java' from string 'javaguides' using delete() method.
public class DeleteExample {
 public static void main(String[] args) {
  StringBuffer buffer = new StringBuffer("javaguides");
  
  // start with index and end with end -1
  StringBuffer subBuffer = buffer.delete(0, 4);
  System.out.println("Delete string 'java' from string 'javaguides' : " + subBuffer.toString());
 }
}
Output:
Delete string 'java' from string 'javaguides' : guides

deleteCharAt(int index)

This method removes the char at the specified position in this sequence. This sequence is shortened by one char.
This method throws StringIndexOutOfBoundsException - if the index is negative or greater than or equal to length().
Example: Example to delete character 'g' from string 'javaguides' using deleteCharAt() method.
public class DeleteCharAtExample {
 public static void main(String[] args) {
  StringBuffer buffer = new StringBuffer("javaguides").deleteCharAt(4);
  System.out.println("Delete char 'g' from string 'javaguides' : " + buffer);
 }
}
Output:
Delete char 'g' from string 'javaguides' : javauides

ensureCapacity(int minimumCapacity)

Ensures that the capacity is at least equal to the specified minimum. If the current capacity is less than the argument, then a new internal array is allocated with greater capacity. The new capacity is the larger of:
  • The minimumCapacity argument.
  • Twice the old capacity, plus 2.
Example: Example to ensure the capacity of string buffer using ensureCapacity() method.
public class EnsureCapacityExample {
 public static void main(String[] args) {
  StringBuffer builder = new StringBuffer();
  builder.ensureCapacity(11);
     System.out.println(builder.capacity());
     builder.ensureCapacity(17);
     System.out.println(builder.capacity());
 }
}
Output:
16
34

getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)

Characters are copied from this sequence into the destination character array dst.
Example: Example to copy characters from this sequence into the destination character array dst.
public class GetCharsExample {
 public static void main(String[] args) {
  StringBuffer buffer = new StringBuffer("javaguides");
  char[] dst = new char[buffer.length()];
  buffer.getChars(0, buffer.length(), dst, 0);
  
  for (char c : dst) {
   System.out.println(c);
  }
 }
}
Output:
j
a
v
a
g
u
i
d
e
s

indexOf() methods

There two forms of indexOf() methods
  • indexOf(String str) - Returns the index within this string of the first occurrence of the specified substring.
  • indexOf(String str, int fromIndex) - Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.
Example: This is a simple program to demonstrate 2 indexOf() methods with different signatures.
public class IndexOfExample {
 public static void main(String[] args) {
  StringBuffer buffer = new StringBuffer("javaguides");
  
  // method 1
  int index = buffer.indexOf("guides");
  System.out.println(index);
  
  // method2
  index = buffer.indexOf("guides", 3);
  System.out.println(index);
 }
}
Output:
4
4

insert() methods

insert() method has 12 overloaded versions. Here are a all of its forms:
  1. StringBuffer insert(int offset, boolean b) - Inserts the string representation of the boolean argument into this sequence.
  2. StringBuffer insert(int offset, char c) - Inserts the string representation of the char argument into this sequence.
  3. StringBuffer insert(int offset, char[] str) - Inserts the string representation of the char array argument into this sequence.
  4. StringBuffer insert(int index, char[] str, int offset, int len) - Inserts the string representation of a subarray of the str array argument into this sequence.
  5. StringBuffer insert(int dstOffset, CharSequence s) - Inserts the specified CharSequence into this sequence.
  6. StringBuffer insert(int dstOffset, CharSequence s, int start, int end) - Inserts a subsequence of the specified CharSequence into this sequence.
  7. StringBuffer insert(int offset, double d) - Inserts the string representation of the double argument into this sequence.
  8. StringBuffer insert(int offset, float f) - Inserts the string representation of the float argument into this sequence.
  9. StringBuffer insert(int offset, int i) - Inserts the string representation of the second int argument into this sequence.
  10. StringBuffer insert(int offset, long l) - Inserts the string representation of the long argument into this sequence.
  11. StringBuffer insert(int offset, Object obj) - Inserts the string representation of the Object argument into this character sequence.
  12. StringBuffer insert(int offset, String str) - Inserts the string into this character sequence.
Example: Below simple program demonstrate the usage of all insert() overloaded methods.
public class InsertExample {
 public static void main(String[] args) {
  
  // 12 insert overloaded method
  StringBuffer builder = new StringBuffer("javaguides").insert(1,true);
  System.out.println(builder.toString());
  
  builder = new StringBuffer("javaguides").insert(0, 'J');
  System.out.println(builder.toString());
  
  char[] chars = {'d','e','v','e','l','o','p','e','r'};
  builder = new StringBuffer("javaguides").insert(4, chars);
  System.out.println(builder.toString());
  
  CharSequence charSequence = new StringBuilder("J2EE/");
  builder = new StringBuffer("javaguides").insert(0, charSequence);
  System.out.println(builder.toString());
  
  builder = new StringBuffer("javaguides").insert(0, 100.0d);
  System.out.println(builder.toString());
  
  builder = new StringBuffer("javaguides").insert(0, 100.0f);
  System.out.println(builder.toString());
  
  builder = new StringBuffer("javaguides").insert(0, 100);
  System.out.println(builder.toString());
  
  builder = new StringBuffer("javaguides").insert(0, 100l);
  System.out.println(builder.toString());
  
  builder = new StringBuffer("javaguides").insert(0, new Object());
  System.out.println(builder.toString());
  
  builder = new StringBuffer("javaguides").insert(0, "ultimate");
  System.out.println(builder.toString());
  
  builder = new StringBuffer("javaguides").insert(0, chars, 0, chars.length);
  System.out.println(builder.toString());
  
  builder = new StringBuffer("javaguides").insert(0, charSequence, 0, charSequence.length());
  System.out.println(builder.toString());
  
 }
}
Output:
jtrueavaguides
Jjavaguides
javadeveloperguides
J2EE/javaguides
100.0javaguides
100.0javaguides
100javaguides
100javaguides
java.lang.Object@15db9742javaguides
ultimatejavaguides
developerjavaguides
J2EE/javaguides

lastIndexOf() methods

lastIndexOf() method has 2 overloaded versions. All its forms:
  1. int lastIndexOf(String str) - Returns the index within this string of the rightmost occurrence of the specified substring.
  2. int lastIndexOf(String str, int fromIndex) - Returns the index within this string of the last occurrence of the specified substring.
Example: This example demonstrates the usage of 2 lastIndexOf() overloaded methods.
public class LastIndexOfExample {
 public static void main(String[] args) {
  StringBuffer buffer = new StringBuffer("javaguides");
  
  // method1
  int lastIndexOf = buffer.lastIndexOf("guides");
  System.out.println(" last index of given string 'guides' in' "
      + buffer.toString()+"' ::  " + lastIndexOf);
  
  // method 2
  lastIndexOf = buffer.lastIndexOf("java", 3);
  System.out.println(" last index of given string 'java' in' "
      + buffer.toString()+"' ::  " + lastIndexOf);
 }
}
Output:
 last index of given string 'guides' in' javaguides' ::  4
 last index of given string 'java' in' javaguides' ::  0

int length()

Returns the length (character count).
Example:
public class LengthExample {
 public static void main(String[] args) {
  StringBuffer buffer = new StringBuffer("javaguides");
  int length = buffer.length();
  System.out.println(" length of the string '" + buffer + "' is :: " + length);
 }
}
Output:
 length of the string 'javaguides' is :: 10

replace(int start, int end, String str)

Replaces the characters in a substring of this sequence with characters in the specified String. The substring begins at the specified start and extends to the character at index end - 1 or to the end of the sequence if no such character exists. First, the characters in the substring are removed and then the specified String is inserted at the start. (This sequence will be lengthened to accommodate the specified String if necessary.)
Example: Example to replace string "ja" with string "java" using replace() method.
public class ReplaceExample {
 public static void main(String[] args) {
  StringBuffer buffer = new StringBuffer("jaguides");
  
  // replace ja with java- start index 0 and end index -1
  StringBuffer subBuffer = buffer.replace(0, 2, "java");
  
  System.out.println(subBuffer);
 }
}
Output:
javaguides

reverse()

Causes this character sequence to be replaced by the reverse of the sequence.
Example: Example to reverse the given String "javaguides" using reverse() method.
public class ReverseExample {
 public static void main(String[] args) {
  StringBuffer buffer = new StringBuffer("javaguides");
  StringBuffer reverse = buffer.reverse();
  System.out.println("Reversed string :" + reverse);
 }
}
Output:
Reversed string :sediugavaj

setCharAt(int index, char ch)

The character at the specified index is set to ch.
Example: Example to set character at index 0 with character 'J' using setCharAt() method.
public class SetCharExample {
 public static void main(String[] args) {
  StringBuffer buffer = new StringBuffer("javaguides");
  buffer.setCharAt(0, 'J');
  System.out.println(buffer.toString());
 }
}
Output;
Javaguides

setLength(int newLength)

Sets the length of the character sequence.
Example: Example to reset the length of the StringBuffer using setLength() method.
public class SetLengthExample {
 public static void main(String[] args) {
  StringBuffer buffer = new StringBuffer("javaguides");
  System.out.println("Before set length to 0 : " + buffer.length());
  buffer.setLength(0);
  System.out.println("After set length to 0 : " + buffer.length());
 }
}
Output:
Before set length to 0 : 10
After set length to 0 : 0

substring() methods

There are two overloaded versions of substring() method:
  1. String substring(int start) - Returns a new String that contains a subsequence of characters currently contained in this character sequence.
  2. String substring(int start, int end) - Returns a new String that contains a subsequence of characters currently contained in this sequence.
Example: This example demonstrates the usage of both overloaded versions of substring() methods.
public class SubStringExample {
 public static void main(String[] args) {
  StringBuffer buffer = new StringBuffer("javaguides");
  
  // substring from start to end
  String subStr = buffer.substring(0, buffer.length());
  System.out.println("substring from 0 to length of the string : " + subStr);
  
  // print java
  System.out.println(buffer.substring(0, 4));
  
  // print guides
  System.out.println(buffer.substring(4, buffer.length()));
 }
}
Output:
substring from 0 to length of the string : javaguides
java
guides

toString()

Returns a string representing the data in this sequence.
Example:
public class ToStringExample {
 public static void main(String[] args) {
  StringBuffer buffer = new StringBuffer("javaguides");
  System.out.println(buffer.toString());
 }
}
Output:
javaguides

trimToSize()

Attempts to reduce storage used for the character sequence.
Example:
public class TrimToSizeExample {
 public static void main(String[] args) {
  StringBuffer buffer = new StringBuffer("javaguides ");
  System.out.println(buffer.capacity());
  buffer.trimToSize();
  System.out.println(buffer.capacity());
 }
}
Output:
27
11

Strings Related Posts

Comments