StringBuilder in Java is a mutable sequence of characters which means using this class you can create mutable strings (String that can be modified). The API provided by StringBuilder class is compatible with StringBuffer with one noticeable difference, with StringBuilder there is no guarantee of synchronization.
When StringBuffer is being used by a single thread it is recommended that StringBuilder be used instead of StringBuffer as it will be faster as there is no synchronization overhead.
Why is StringBuilder class required
You may be wondering why is StringBuilder or StringBuffer class required when String class is already there with an extensive API.
In the post String in Java we have already seen that String objects are immutable and their values cannot be changed after they are created. Because of this immutability property when you use a String modification method like concatenation what actually happens is that a new String is created and returned that contains the result of the operation. That may lead to creation of lots of intermediate String objects if String is modified several times which in turn means more memory being used for these intermediate objects.
Using StringBuilder or StringBuffer you can avoid this problem of creating several objects as these classes are mutable.
Important points about Java StringBuilder
Some of the important points about StringBuilder class.
- StringBuilder in Java provides much of the functionality of String class with one prominent deviation that StringBuilder is mutable.
- StringBuilder has an API compatible with StringBuffer except one design difference StringBuilder is not synchronized so it is not thread safe like StrinBuffer.
- Every StringBuilder is created with a capacity. As long as the length of the character sequence contained in the string builder does not exceed the capacity, it is not necessary to allocate a new internal buffer. If the internal buffer overflows, it is automatically made larger.
Java StringBuilder Constructors
There are four constructors in StringBuilder class.
- StringBuilder()- Constructs an empty string builder and an initial capacity of 16 characters.
StringBuilder sb = new StringBuilder();
- StringBuilder(int capacity)- Constructs a string builder with no characters in it and an initial capacity specified by the capacity argument.
StringBuilder sb = new StringBuilder(30);
- StringBuilder(CharSequence seq)- Constructs a string builder that contains the same characters as the specified CharSequence. Here CharSequence is an interface which is implemented by CharBuffer, Segment, String, StringBuffer, StringBuilder.
- StringBuilder(String str)- Constructs a string builder initialized to the contents of the specified string.
StringBuilder sb = new StringBuilder("Hello");
Java StringBuilder method examples
append method
append method in StringBuilder class is overloaded so as to accept data of any type. This method appends the string representation of the given data type to existing buffer. The append method always adds these characters at the end of the buffer.
public class StringLiteral { public static void main(String[] args) { StringBuilder sb = new StringBuilder("Hello"); sb.append(" "); //chaining several appends sb.append("World").append(" ").append(123); System.out.println("Appended String- " + sb.toString()); } }Output
Appended String- Hello World 123
As you can see from the example append is used with both String and int as argument as it is overloaded for these data types. You can also chain several append methods as done in the example.
insert methodinsert method is also overloaded in StringBuilder class so as to accept data of any type. This method is used to insert the string representation of the given data type to existing buffer. The insert method adds the characters at a specified point.
insert method takes two arguments first an integer indicating the position where characters are to be inserted in the buffer and second argument is the text to be inserted.
public class StringLiteral { public static void main(String[] args) { StringBuilder sb = new StringBuilder("Hello"); sb.insert(5, " World"); System.out.println("String after insert- " + sb); } }Output
String after insert- Hello Worldlength and capacity methods
- capacity()- Returns the current capacity of the StringBuilder.
- length()- Returns the number of characters in this sequence.
public class StringLiteral { public static void main(String[] args) { StringBuilder sb = new StringBuilder(30); sb.append("Hello"); System.out.println("Capacity of StringBuilder- " + sb.capacity()); System.out.println("Length of StringBuilder- " + sb.length()); } }Output
Capacity of StringBuilder- 30 Length of StringBuilder- 5
Here you can see that StringBuilder is created with the capacity as 30 so the capacity is displayed as 30 where as number of characters in the buffer is 5 so the length is displayed as 5.
reverse method- reverse()- Reverses the existing StringBuilder.
public class StringLiteral { public static void main(String[] args) { StringBuilder sb = new StringBuilder("Hello"); System.out.println("Reversed- " + sb.reverse()); } }Output
Reversed- olleHreplace method
- replace(int start, int end, String str)- Replaces the characters in a substring of this sequence (start to end-1) with characters in the specified String.
public class StringLiteral { public static void main(String[] args) { StringBuilder sb = new StringBuilder("Hello"); sb.replace(3, 5, "ena"); System.out.println("String- " + sb); } }Output
String- Helenadelete and deleteCharAt methods
- delete(int start, int end)- Removes the characters in a substring of this sequence. start which indicates the beginning index is inclusive where as end which indicates the ending index is exclusive.
- deleteCharAt(int index)- Removes the char at the specified position in this sequence.
public class StringLiteral { public static void main(String[] args) { StringBuilder sb = new StringBuilder("Hello"); sb.delete(1, 3); System.out.println("After deletion- " + sb); System.out.println("Length of StringBuilder- " + sb.length()); } }Output
After deletion- Hlo Length of StringBuilder- 3
public class StringLiteral { public static void main(String[] args) { StringBuilder sb = new StringBuilder("Hello"); sb.deleteCharAt(4); System.out.println("After deletion- " + sb); System.out.println("Length of StringBuilder- " + sb.length()); } }Output
After deletion- Hell Length of StringBuilder- 4
Reference: https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/lang/StringBuilder.html
That's all for the topic Java StringBuilder With Method Examples. If something is missing or you have something to share about the topic please write a comment.
You may also like
- Java StringJoiner Class With Method Examples
- Constant String Pool in Java
- Remove Spaces From a String in Java - trim(), strip()
- Check if Given String Subsequence of Another String in Java
- Java CopyOnWriteArraySet With Examples
- BiPredicate Functional Interface Java Examples
- Polymorphism in Python With Examples
- Spring Boot + Spring Data REST Example
No comments:
Post a Comment