0% found this document useful (0 votes)
6 views

6.3 Java StringBuilder Class A

Uploaded by

mrnirajbro
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

6.3 Java StringBuilder Class A

Uploaded by

mrnirajbro
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Java StringBuilder Class

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.

Important Constructors of StringBuilder class

Constructor Description

StringBuilder() It creates an empty String Builder with the initial capacity of 16.

StringBuilder(String str) It creates a String Builder with the specified string.

StringBuilder(int It creates an empty String Builder with the specified capacity as


length) length.

Important methods of StringBuilder class

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 capacity() It is used to return the current capacity.

public int length() It is used to return the length of the string i.e. total number of
characters.

Java StringBuilder Examples


Let's see the examples of different methods of StringBuilder class.

1) StringBuilder append() method


The StringBuilder append() method concatenates the given argument with this String.

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. }

You might also like