StringBuilder in Java with Examples
The StringBuilder class in java is the same as the String class except it is mutable i.e. it can be changed.
What is StringBuilder ?
It is a mutable sequence of characters. This class provides an API compatible with StringBuffer, but with no guarantee of synchronization. This class is designed for use as a drop-in replacement for StringBuffer in places where the string buffer was being used by a single thread (as is generally the case). Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations.
Instances of StringBuilder are not safe for use by multiple threads. If such synchronization is required then it is recommended that StringBuffer be used.
Every StringBuilder has a capacity. As long as the length of the character sequence contained in the StringBuilder does not exceed the capacity, it is not necessary to allocate a new internal buffer array. If the internal buffer overflows, it is automatically made larger.
Table of Content :
- Introduction
- What is StringBuilder ?
- StringBuilder Class Declaration
- StringBuilder in Java with Examples
- Difference between StringBuffer and StringBuilder
- Articles/Questions related to StringBuilder in Java
- Summary
StringBuilder implements Comparable but does not override equals. Thus, the natural ordering of StringBuilder is inconsistent with equals. Care should be exercised if StringBuilder objects are used as keys in a SortedMap or elements in a SortedSet. See Comparable , SortedMap, or SortedSet for more information.
Unless otherwise noted, passing a null argument to a constructor or method in this class will cause a
NullPointerException to be thrown.
StringBuilder Class Declaration
The following is the declaration for java.lang.StringBuilder class:
public final class StringBuilder
extends Object
implements Serializable, CharSequence
}
}
StringBuilder has 4 constructors.
1). StringBuilder sb = new StringBuilder();
It creates an empty StringBuilder object with a default initial capacity "16". Once the StringBuilder object reaches its maximum capacity a new StringBuilder object will be created with newCapacity = (currentcapacity+1)*2.
public class StringBuilder1 {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
System.out.println(sb.capacity()); //16
sb.append("hello world");
System.out.println(sb.capacity()); //16
sb.append("Welcome");
System.out.println(sb.capacity()); //34
}
}
2). StringBuilder sb = new StringBuilder(int initialcapacity);
It creates an empty StringBuilder object with the specified initial capacity.
public class StringBuilder2 {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder(19);
System.out.println(sb.capacity()); //19
}
}
3). StringBuilder sb=new StringBuilder (String s);
It creates an equivalent StringBuilder object for the given String with capacity = s.length()+16;.
public class StringBuffer3 {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello World");
System.out.println(sb.capacity()); //27
}
}
}
4). StringBuilder(CharSequence seq);
It Constructs a string builder that contains the same characters as the specified CharSequence.
Important methods of StringBuilder :
1). public int length();
It returns the number of characters present in the StringBuilder.
StringBuilder sb=new StringBuilder("Hello World");
System.out.println(sb.length());//11
2). public int capacity();
It returns the total no of characters StringBuilder can accommodate(hold).
StringBuilder sb=new StringBuilder("Hello World");
System.out.println(sb.capacity());//27
3). public char charAt(int index);
It returns the character located at the specified index.
public class StringBuilder4 {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello World Welcome");
System.out.println(sb.length()); //19
System.out.println(sb.capacity()); //35
System.out.println(sb.charAt(15)); //c
System.out.println(sb.charAt(30)); //Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 30
}
}
}
4). public void setCharAt(int index, char ch);
It is used to replace the character locating at a specified index with the provided character.
public class StringBuilder5 {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello World Welcome Sara");
System.out.println(sb);
sb.setCharAt(20, 'T');
System.out.println(sb);
}
}
Output:
Hello World Welcome Sara
Hello World Welcome Tara
5). public StringBuilder append(String s);
This method will concatenate the string representation of any type of data to the end of the StringBuilder object.
The
append() method has several overloaded forms..
public StringBuilder append(String s);
public StringBuilder append(int i);
public StringBuilder append(long l);
public StringBuilder append(boolean b);
public StringBuilder append(double d);
public StringBuilder append(float f);
public StringBuilder append(int index, Object o);
public class StringBuilder5 {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Sara");
System.out.println(sb); //Sara
sb.setCharAt(0, 'T');
System.out.println(sb); //Tara
}
}
6). insert()
This method inserts one string into another string.
append() method has several overloaded forms.
public StringBuilder insert(int index,String s);
public StringBuilder insert(int index,int i);
public StringBuilder insert(int index,long l);
public StringBuilder insert(int index,double d);
public StringBuilder insert(int index,boolean b);
public StringBuilder insert(int index,float f);
public StringBuilder insert(int index, Object o);
]
public class StringBuilder6 {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello World Welcome to !");
System.out.println(sb); //Hello World Welcome to !
sb.insert(7, "xyz");
sb.insert(26, "2021");
System.out.println(sb); //Hello Wxyzorld Welcome to 2021!
}
}
7).
public StringBuilder delete(int begin,int end);
It is used to delete characters from begin index to the end n-1 index.
8).
public StringBuilder deleteCharAt(int index);
It is used to delete the character locating at the specified index.
public class StringBuilder7 {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello World Welcome to 2021!");
System.out.println(sb); //Hello World Welcome to 2021!
sb.delete(6, 13);
System.out.println(sb); // Hello elcome to 2021!
sb.deleteCharAt(3);
System.out.println(sb); // Helo elcome to 2021!
}
}
9). public StringBuilder reverse();
It is used to reverse the characters within a StringBuilder object.
public class StringBuilder8 {
public static void main(String[] args) {
StringBuilder str = new StringBuilder("Sara");
str.reverse();
System.out.println(str); // Sara
System.out.println(str); // araS
}
}
10). public void setLength(int length);
It considers only the specified no of characters and removes all the remaining characters.
public class StringBuilder9 {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello World");
System.out.println(sb); //Hello World
sb.setLength(5);
System.out.println(sb); //Hello
}
}
11). public void trimToSize();
It is used to deallocate the extra allocated free memory such that capacity and size are equal.
public class StringBuilder10 {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder(1000);
System.out.println(sb.capacity()); //1000
sb.append("Sara");
System.out.println(sb.capacity()); //1000
sb.trimToSize();
System.out.println(sb.capacity()); //4
}
}
12). public void ensureCapacity(int initialcapacity);
It is used to increase the capacity dynamically based on our requirement.
public class StringBuilder11 {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
System.out.println(sb.capacity()); //16
sb.ensureCapacity(1000);
System.out.println(sb.capacity()); //1000
}
}
Difference between StringBuffer and StringBuilder
StringBuffer | StringBuilder |
---|---|
Introduced in Java 1.0. | Introduced in Java 1.5. |
At a time only one thread is allowed to operate on the StringBuffer object hence StringBuffer object is Thread safe. | At a time Multiple Threads are allowed to operate simultaneously on the StringBuilder object hence StringBuilder is not Thread safe |
StringBuffer is less efficient as compare to StringBuilder. | StringBuilder is more efficient as compared to StringBuffer. |
It increases the waiting time of the Thread and hence relatively performance is low. | Threads are not required to wait and hence relatively performance is high. |
Articles/Questions related to StringBuilder in Java
Java adding New Line in a String
Java String split() method Examples
String lastIndexOf() method examples in Java
String indexOf() method example in Java
String array in Java
How to check if an enum contains String
StringBuffer in Java with Examples
In this article, we have seen StringBuilder in Java with Examples
0 Comments
Post a Comment