Methods | Description |
---|---|
public StringBuilder append(String s) | Append the specified string with the given string. |
public StringBuilder insert(int offset, String s) | Insert the specified string with given string at the specified position. |
public StringBuilder delete(int start, int end) | Delete substring from specified start index to end index. |
public StringBuilder replace(int start, int end, String s) | Replace the characters in a substring of current sequence with the character in the specified new string. |
public StringBuilder reverse() | Reverse the given string. |
public StringBuilder toString() | Returns a string representing the data in this sequence. |
void setLength(int newLength) | Set the length of the character sequence. The value of argument newLength is always positive, otherwise it will throw IndexOutOfBoundException. |
public ensureCapacity(int minimumCapacity) | Ensure that the capacity is at least equal to given minimum capacity. |
public class StringBuilderDemo
{
public static void main(String args[])
{
StringBuilder sb1 = new StringBuilder("Tutorial");
StringBuilder sb2 = new StringBuilder("Java Toturials");
StringBuilder sb3 = new StringBuilder("Welcome");
StringBuilder sb4 = new StringBuilder("ABC");
//append
sb1.append("Ride");
System.out.println("sb1: "+sb1);
//delete
sb2.delete(0, 5);
System.out.println("After delete sb1= "+sb2);
//reverse
sb3.reverse();
System.out.println("Reverse of sb2= "+sb3);
//charAt()
for (int i = 0; i <= sb4.length()-1; i++)
{
System.out.println("Character at index "+i+" is: "+sb4.charAt(i));
}
}
}
String | StringBuilder |
---|---|
The object of String class is immutable. | The object of Stringbuffer class is mutable. |
Creates string in fixed size. | Creates string in dynamically flexible. |
The performance of String class is slow when performing concatenation. | It performs better while performing concatenation. |
Growing and shrinking in size is not possible. | Growing and shrinking in size is possible. |
String class overrides the equals () method of object class. | StringBuffer class doesn’t override the equals (). |
//Write a program to check the performance of String and StringBuilder while concatenation.
public class ConcatTest
{
public static String concatWithString()
{
String s = "Tutorial";
for (int i=0; i<10000; i++)
{
s = s + "Ride";
}
return s;
}
public static String concatWithStringBuffer()
{
StringBuffer sb = new StringBuffer("Tutorial");
for (int i=0; i<10000; i++)
{
sb.append("Ride");
}
return sb.toString();
}
public static void main(String[] args)
{
long start = System.currentTimeMillis();
concatWithString();
System.out.println("Time taken by String: " + (System.currentTimeMillis() - start) + "ms");
start = System.currentTimeMillis();
concatWithStringBuffer();
System.out.println("Time taken by StringBuffer: " + (System.currentTimeMillis() - start) + "ms");
}
}