6.3 Java StringBuilder Class A
6.3 Java StringBuilder Class A
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.
Constructor Description
StringBuilder() It creates an empty String Builder with the initial capacity of 16.
Method Description
public StringBuilder It is used to append the specified string with this string. The
append(String s) append() method is overloaded like append(char),
append(boolean), append(int), append(float), append(double)
etc.
public StringBuilder insert(int It is used to insert the specified string with this string at the
offset, String s) specified position. The insert() method is overloaded like
insert(int, char), insert(int, boolean), insert(int, int), insert(int,
float), insert(int, double) etc.
public StringBuilder It is used to replace the string from specified startIndex and
replace(int startIndex, int endIndex.
endIndex, String str)
public StringBuilder delete(int It is used to delete the string from specified startIndex and
startIndex, int endIndex) endIndex.
public StringBuilder reverse() It is used to reverse the string.
public int length() It is used to return the length of the string i.e. total number of
characters.
StringBuilderExample.java
1. class StringBuilderExample{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello ");
4. sb.append("Java");//now original string is changed
5. System.out.println(sb);//prints Hello Java
6. }
7. }
Output:
Hello Java
2) StringBuilder insert() method
The StringBuilder insert() method inserts the given string with this string at the given
position.
StringBuilderExample2.java
1. class StringBuilderExample2{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello ");
4. sb.insert(1,"Java");//now original string is changed
5. System.out.println(sb);//prints HJavaello
6. }
7. }