Programming in Java
Topic: StringBuilder Class
Introduction
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.
StringBuilder Constructors
StringBuilder defines these four constructors:
◦ StringBuilder( )
◦ StringBuilder(int cap)
◦ StringBuilder(String str)
The default constructor reserves room for 16 characters without
reallocation.
By allocating room for a few extra characters(size +16),
StringBuilder reduces the number of reallocations that take place.
Brain Storming
StringBuilder sb = new StringBuilder();
System.out.println(sb.capacity()); //16
StringBuilder sb = new StringBuilder(65);
System.out.println(sb.capacity()); //65
StringBuilder sb = new StringBuilder(“A”);
System.out.println(sb.capacity()); //17
StringBuilder sb = new StringBuilder('A');
System.out.println(sb.capacity()); //65
StringBuilder Methods
length( ) and capacity( )
The current length of a StringBuilder can be found via the length( )
method, while the total allocated capacity can be found through the
capacity( ) method.
int length( )
int capacity( )
Example:
class StringBuilderDemo {
public static void main(String args[]) {
StringBuilder sb = new StringBuilder(“New Zealand");
System.out.println("length = " + sb.length()); //11
System.out.println("capacity = " + sb.capacity()); //27
}
}
ensureCapacity( )
The ensureCapacity() method of StringBuffer class ensures
the capacity to at least equal to the specified
minimumCapacity.
If the current capacity of StringBuffer < the argument
minimumCapacity, then a new internal array is allocated with
greater capacity.
If the minimumCapacity argument > twice the old capacity,
plus 2 then new capacity is equal to minimumCapacity else
new capacity is equal to twice the old capacity, plus 2.
If the minimumCapacity argument passed as parameter < 0,
this method takes no action..
Important
When the length of StringBuilder becomes larger than the
capacity then memory reallocation is done:
In case of StringBuilder, reallocation of memory is done using
the following rule:
If the new_length <= 2*(original_capacity + 1), then
new_capacity = 2*(original_capacity + 1)
Else, new_capacity = new_length.
class hello {
public static void main(String[] args)
{
StringBuffer str = new StringBuffer();
System.out.println("Before ensureCapacity "
+ "method capacity = "
+ str.capacity()); //16
str.ensureCapacity(18);
System.out.println("After ensureCapacity"
+ " method capacity = "
+ str.capacity()); //34
}
}
class hello {
public static void main(String[] args)
{
StringBuffer str
= new StringBuffer("Geeks For Geeks");
System.out.println("Before ensureCapacity "
+ "method capacity = "
+ str.capacity()); //31
str.ensureCapacity(42);
System.out.println("After ensureCapacity"
+ " method capacity = "
+ str.capacity()); //64
}
}
StringBuffer sb = new StringBuffer();
System.out.println("default capacity of buffer: " + sb.capacity());
StringBuffer sb1 = new StringBuffer("hello");
System.out.println("string1: " + sb1);
System.out.println("capacity: " + sb1.capacity());
sb1.ensureCapacity(20);
System.out.println("new capacity: " + sb1.capacity());
StringBuffer sb2 = new StringBuffer("programming");
System.out.println("string2: " + sb2);
System.out.println("old capacity: " + sb2.capacity());
sb2.ensureCapacity(28);
System.out.println("new capacity: "+sb2.capacity());
setLength( )
The setLength(int newLength) method of StringBuilder class is
used to set the new length of the character sequence. The new
length of character sequence becomes to specified newLength
argument.
If the newLength argument is less than the current length, the new
length of character sequence will change to newLength. On the
other hand, if the newLength argument is greater than the current
length then the null character(s) '\u0000' are appended so that length
becomes the newLength argument.
public void setLength(int newLength) .
public static void main(String[] args) {
StringBuilder sb = new
StringBuilder("stringbuilder");
System.out.println("string: "+sb);
System.out.println("length: "+sb.length());
sb.setLength(6);
System.out.println("set new length:
"+sb.length());
System.out.println("new sequence: "+sb);
}
}
charAt( ) and setCharAt( )
The value of a single character can be obtained from a
StringBuilder via the charAt( ) method.
We can set the value of a character within a StringBuilder
using setCharAt( ).
char charAt(int index)
void setCharAt(int index, char ch)
1. StringBuilder sb = new StringBuilder("abc");
2. System.out.println("string = " + sb); //abc
3.
System.out.println("character at index 1 = " + sb.charA
t(1)); //b
1.
2. sb.setCharAt(1, 'x');
3. System.out.println("new string = " + sb); //axc
4. System.out.println("character at index 1 = " + sb.ch
arAt(1)); // x
getChars( )
getChars( ) method is used to copy a substring of a
StringBuilder into an array.
void getChars(int sourceStart, int sourceEnd, char target[ ],
int targetStart)
append( )
The append( ) method concatenates the string representation
of any other type of data to the end of the invoking
StringBuilder object.
It has several overloaded versions.
◦ StringBuilder append(String str)
◦ StringBuilder append(int num)
◦ StringBuilder append(Object obj)
Example
class appendDemo {
public static void main(String args[]) {
String s;
int a = 42;
StringBuilder sb = new StringBuilder(40);
s = sb.append("a = ").append(a).append("!")
.toString();
System.out.println(s);
}
}
// a= 42!
insert( )
The insert( ) method inserts one string into another.
It is overloaded to accept values of all the simple types, plus
Strings, Objects, and CharSequences.
This string is then inserted into the invoking StringBuilder
object.
◦ StringBuilder insert(int index, String str)
◦ StringBuilder insert(int index, char ch)
◦ StringBuilder insert(int index, Object obj)
Example
class insertDemo {
public static void main(String args[]) {
StringBuilder sb = new StringBuilder("I Java!");
sb.insert(2, "like ");
System.out.println(sb);
}
}
// I like Java!
reverse( )
Used to reverse the characters within a StringBuilder object.
This method returns the reversed object on which it was called.
StringBuilder reverse()
Example:
class ReverseDemo {
public static void main(String args[]) {
StringBuilder s = new StringBuilder(“ Apple");
System.out.println(s);
s.reverse();
System.out.println(s);
}
}
delete( ) and deleteCharAt( )
Used to delete characters within a StringBuilder.
StringBuilder delete(int startIndex, int endIndex)
StringBuilder deleteCharAt(int index)
The delete( ) method deletes a sequence of characters from the
invoking object (from startIndex to endIndex-1).
The deleteCharAt( ) method deletes the character at the
specified index.
It returns the resulting StringBuilder object.
Example
class deleteDemo {
public static void main(String args[]) {
StringBuilder sb = new StringBuilder(“She is not a good
girl.”);
sb.delete(7, 11);
System.out.println("After delete: " + sb);
sb.deleteCharAt(7);
System.out.println("After deleteCharAt: " + sb);
}
}
After delete: She is a good girl.
After deleteCharAt: She is good girl.
replace( )
Used to replace one set of characters with another set inside a
StringBuilder object.
StringBuilder replace(int startIndex, int endIndex, String str)
The substring being replaced is specified by the indexes startIndex
and endIndex.
Thus, the substring at startIndex through endIndex–1 is replaced.
The replacement string is passed in str.
The resulting StringBuilder object is returned.
Example
class replaceDemo {
public static void main(String args[]) {
StringBuilder sb = new StringBuilder("This is a
test.");
sb.replace(5, 7, "was");
System.out.println("After replace: " + sb);
}
}
After replace: This was a test.
substring( )
Used to obtain a portion of a StringBuilder by calling substring(
).
String substring(int startIndex)
String substring(int startIndex, int endIndex)
The first form returns the substring that starts at startIndex and
runs to the end of the invoking StringBuilder object.
The second form returns the substring that starts at startIndex
and runs through endIndex–1.
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("java
is a programming language");
System.out.println("string = "+sb);
String subsequence= sb.substring(10,22);
//subsequence from start index 10 and end
index 22
System.out.println("subsequence from
index 10 to 22= "+subsequence);
}
string = java is a programming language
subsequence from index 10 to 22= programming