StringBuilder class methods
You can create a mutable string using the StringBuilder class. This is the only difference in the StringBuffer class and the StringBuilder class that the StringBuilder class is non-synchronised.
Constructors
Below are the constructors that can be used in StringBuilder class-
- StringBuilder()- it will create an empty string buffer with the initial capacity of 16.
- StringBuilder(String str)- it will create a string buffer with the specified string.
- StringBuilder(int length)- it will create an empty string buffer with the specified capacity as length.
Methods
You can use the below methods to change and modify the string.
append() method- this method will append the provided string with this string. You can use this method for method overloading.
Example-
class Simple{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Welcome");
sb.append(" Here");
System.out.println(sb);
}
}
Output-
insert() method- this method will insert the provided string to another string at the given position.
Example-
class Simple{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Welcome ");
sb.insert(1,"Sam");
System.out.println(sb);
}
}
Output-
replace() method- this method will allow you to replace the specified string from the provided beginIndex and endIndex.
Example-
class Simple{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Welcome ");
sb.replace(1,3,"Sam");
System.out.println(sb);
}
}
Output-
delete() method- this method will allow you to delete the specified string from the provided beginIndex and endIndex.
Example-
class Simple{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Welcome ");
sb.delete(1,3);
System.out.println(sb);
}
}
Output-
reverse() method- this method will reverse the current string.
Example-
class Simple{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Welcome ");
sb.reverse();
System.out.println(sb);
}
}
Output-
capacity() method- this method will return the buffer’s current capacity.
Example-
class Simple{
public static void main(String args[]){
StringBuilder sb=new StringBuilder();
System.out.println(sb.capacity());
sb.append("welcome");
System.out.println(sb.capacity());
sb.append("hello");
System.out.println(sb.capacity());
}
}
Output-