StringBuilder Class Methods in Java

In this article, we will learn all important Java StringBuilder class methods with examples.

Java StringBuilder class is used to create mutable (modifiable) string. The Java StringBuilder class is same as StringBuffer class except that it is non-synchronized. It is available since JDK 1.5.
As we know instances of StringBuilder are not safe for use by multiple threads. If such synchronization is required then it is recommended that StringBuffer is used.
The diagram shows a list of methods offered by StringBuilder Class.


Let's discuss all  StringBuilder class methods with examples. 

StringBuilder APIs/Methods with Examples

append() methods

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

  StringBuilder builder;
  // append String

  // Append String
  builder = new StringBuilder().append("guides");
  System.out.println("Append string : " + builder);
  
  // Append char
  builder = new StringBuilder().append('c');
  System.out.println("Append char : " + builder);
  // Append Object
  builder = new StringBuilder().append(new Object().getClass());
  System.out.println("Append Object : " + builder);
  
  // Append chars
  char[] chars = { 'j', 'a', 'v', 'a' };
  builder = new StringBuilder().append(chars);
  System.out.println("Append chars : " + builder);
  
  // Append charSequence
  builder = new StringBuilder().append("charSequence");
  System.out.println("Append charSequence : " + builder);
  
  // Append Double
  builder = new StringBuilder().append(10.0d);
  System.out.println("Append Double : " + builder);
  
  // Append Float
  builder = new StringBuilder().append(10.5f);
  System.out.println("Append Float : " + builder);
  
  // Append int
  builder = new StringBuilder().append(100);
  System.out.println("Append int : " + builder);
  
  // Append Boolean
  builder = new StringBuilder().append(true);
  System.out.println("Append Boolean : " + builder);
  
  // Append Long
  builder = new StringBuilder().append(100000);
  System.out.println("Append Long : " + builder);
  
  // Appends the specified StringBuffer to this sequence
  builder = new StringBuilder().append(new StringBuffer("stringbuffer"));
  System.out.println("Append StringBuffer : " + builder);
  
  // Appends the string representation of a subarray of the char array.
  builder = new StringBuilder().append(chars, 1, 3);
  System.out.println("Append subarray of the char array : " + builder);
  
  // Appends a subsequence of the specified CharSequence to this sequence.
  builder = new StringBuilder().append("javaguides", 0, 9);
  System.out.println("Append CharSequence : " + builder);
  
  // Appends the string representation of the codePoint argument to this
  // sequence.
  builder = new StringBuilder("javaguides").appendCodePoint(0);
  System.out.println("Append appendCodePoint : " + builder);

 }
}
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 : 100000
Append StringBuffer : stringbuffer
Append subarray of the char array : ava
Append CharSequence : javaguide
Append appendCodePoint : javaguides

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) {
  StringBuilderbuilder = new StringBuilder("javaguides");
  int capacity = builder.capacity();
  
  // inital capacity
  System.out.println(new StringBuilder().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 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.
StringBuilder builder = new StringBuilder("Welcome to string handling guide");
char ch1 = builder.charAt(0);
char ch2 = builder.charAt(5);
char ch3 = builder.charAt(11);
char ch4 = builder.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 how to get first and last character of the string
public static void charAtExample2() {
StringBuilder builder = new StringBuilder("Java Guides");
int strLength = builder .length() - 1;
// Fetching first character
System.out.println("Character at 0 index is: " + builder .charAt(0));
// The last Character is present at the string length-1 index
System.out.println("Character at last index is: " + builder .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) {
  StringBuilder builder = new StringBuilder("javaguides");
  int unicode = builder.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)

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().
Example:
public class CodePointBeforeExample {
 public static void main(String[] args) {
  StringBuilder builder = new StringBuilder("javaguides");
  int unicode = builder.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) {
  StringBuilder builder = new StringBuilder("javaguides");
  System.out.println("length of the string :: " + builder.length());
  int unicode = builder.codePointCount(0, builder.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) {
  StringBuilder builder = new StringBuilder("javaguides");
  
  // start with index and end with end -1
  StringBuilder subBuilder = buffer.delete(0, 4);
  System.out.println("Delete string 'java' from string 'javaguides' : " + subBuilder.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) {
  StringBuilder subBuilder = new StringBuilder("javaguides").deleteCharAt(4);
  System.out.println("Delete char 'g' from string 'javaguides' : " + subBuilder1);
 }
}
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 capacity of string buffer using ensureCapacity() method.
public class EnsureCapacityExample {
 public static void main(String[] args) {
  StringBuilder builder = new StringBuilder();
  builder.ensureCapacity(11);
     System.out.println(builder.capacity());
 }
}
Output:
16

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) {
  StringBuilder builder = new StringBuilder("javaguides");
  char[] dst = new char[builder.length()];
  builder.getChars(0, builder.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) {
  StringBuilder builder = new StringBuilder("javaguides");
  
  // method 1
  int index = builder.indexOf("guides");
  System.out.println(index);
  
  // method2
  index = builder.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. StringBuilder insert(int offset, boolean b) - Inserts the string representation of the boolean argument into this sequence.
  2. StringBuilder insert(int offset, char c) - Inserts the string representation of the char argument into this sequence.
  3. StringBuilder insert(int offset, char[] str) - Inserts the string representation of the char array argument into this sequence.
  4. StringBuilder 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. StringBuilder insert(int dstOffset, CharSequence s) - Inserts the specified CharSequence into this sequence.
  6. StringBuilder insert(int dstOffset, CharSequence s, int start, int end) - Inserts a subsequence of the specified CharSequence into this sequence.
  7. StringBuilder insert(int offset, double d) - Inserts the string representation of the double argument into this sequence.
  8. StringBuilder insert(int offset, float f) - Inserts the string representation of the float argument into this sequence.
  9. StringBuilder insert(int offset, int i) - Inserts the string representation of the second int argument into this sequence.
  10. StringBuilder insert(int offset, long l) - Inserts the string representation of the long argument into this sequence.
  11. StringBuilder insert(int offset, Object obj) - Inserts the string representation of the Object argument into this character sequence.
  12. StringBuilder 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
  StringBuilder builder = new StringBuilder("javaguides").insert(1, true);
  System.out.println(builder.toString());

  builder = new StringBuilder("javaguides").insert(0, 'J');
  System.out.println(builder.toString());

  char[] chars = { 'd', 'e', 'v', 'e', 'l', 'o', 'p', 'e', 'r' };
  builder = new StringBuilder("javaguides").insert(4, chars);
  System.out.println(builder.toString());

  CharSequence charSequence = new StringBuilder("J2EE/");
  builder = new StringBuilder("javaguides").insert(0, charSequence);
  System.out.println(builder.toString());

  builder = new StringBuilder("javaguides").insert(0, 100.0d);
  System.out.println(builder.toString());

  builder = new StringBuilder("javaguides").insert(0, 100.0f);
  System.out.println(builder.toString());

  builder = new StringBuilder("javaguides").insert(0, 100);
  System.out.println(builder.toString());

  builder = new StringBuilder("javaguides").insert(0, 100l);
  System.out.println(builder.toString());

  builder = new StringBuilder("javaguides").insert(0, new Object());
  System.out.println(builder.toString());

  builder = new StringBuilder("javaguides").insert(0, "ultimate");
  System.out.println(builder.toString());

  builder = new StringBuilder("javaguides").insert(0, chars, 0, chars.length);
  System.out.println(builder.toString());

  builder = new StringBuilder("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. Here are a all of 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) {
  StringBuilder builder = new StringBuilder("javaguides");

  // method1
  int lastIndexOf = builder.lastIndexOf("guides");
  System.out.println(" last index of given string 'guides' in' "
    + builder.toString() + "' ::  " + lastIndexOf);

  // method 2
  lastIndexOf = builder.lastIndexOf("java", 3);
  System.out.println(" last index of given string 'java' in' "
     + builder.toString() + "' ::  " + lastIndexOf);
 }
}
Output:
 last index of given string 'guides' in' javaguides' ::  4
 last index of given string 'java' in' javaguides' ::  0

length()

Returns the length (character count).
Example:
public class LengthExample {
 public static void main(String[] args) {
  StringBuilder builder = new StringBuilder("javaguides");
  int length = builder.length();
  System.out.println(" length of the string '" + builder + "' 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 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) {
  StringBuilder buffer = new StringBuilder("jaguides");
  
  // replace ja with java- start index 0 and end index -1
  StringBuilder 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) {
  StringBuilder builder = new StringBuilder("javaguides");
  StringBuilder reverse = builder.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) {
  StringBuilder builder = new StringBuilder("javaguides");
  builder.setCharAt(0, 'J');
  System.out.println(builder.toString());
 }
}
Output;
Javaguides

setLength(int newLength)

Sets the length of the character sequence.
Example: Example to reset the length of the StringBuilder using setLength() method.
public class SetLengthExample {
 public static void main(String[] args) {
  StringBuilder builder = new StringBuilder("javaguides");
  System.out.println("Before set length to 0 : " + builder.length());
  builder.setLength(0);
  System.out.println("After set length to 0 : " + builder.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) {
  StringBuilder builder = new StringBuilder("javaguides");
  // substring from start to end
  String subStr = buffer.substring(0, builder.length());
  System.out.println("substring from 0 to length of the string : " + subStr);
  
  // print java
  System.out.println(builder.substring(0, 4));
  
  // print guides
  System.out.println(builder.substring(4, builder.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) {
  StringBuilder builder = new StringBuilder("javaguides");
  System.out.println(builder.toString());
 }
}
Output:
javaguides

trimToSize()

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

Reference


Comments