StringBuilder Class in Java with Examples
Get Job-ready: Java Course with 45+ Real-time Projects! - Learn Java
The StringBuilder class in Java enables the creation of adjustable sequences of characters. Unlike immutable Strings, StringBuilder allows modifying the character content after creation. This makes StringBuilder worthwhile when you frequently change the string value without creating new String objects.
StringBuilder is similar in some ways to StringBuffer – both allow mutable strings. However, a key difference is that StringBuilder is non-synchronized for use by a single thread, while StringBuffer is synchronized and thread-safe.
StringBuilder’s advantage is that it performs better in single-threaded contexts since it avoids the overhead of synchronization. However, it cannot be safely used by multiple threads concurrently, so StringBuffer is more suitable.
Constructors in Java StringBuilder Class
- StringBuilder() – Creates an empty string builder with default initial capacity.
- StringBuilder(int capacity) – Creates an empty string builder with a specified initial capacity.
- StringBuilder(CharSequence seq) – Creates string builder containing the same characters as a passed sequence.
- StringBuilder(String str) – Creates string builder initialized with same chars as passed string.
Example:
public class Main { public static void main(String[] args) { StringBuilder sb1 = new StringBuilder(); StringBuilder sb2 = new StringBuilder(50); CharSequence cs = "Hello"; StringBuilder sb3 = new StringBuilder(cs); String s = "World"; StringBuilder sb4 = new StringBuilder(s); System.out.println(sb1); System.out.println(sb2); System.out.println(sb3); System.out.println(sb4); } }
Output:
Hello
World
Methods in Java StringBuilder
StringBuilder provides a variety of methods to modify a sequence of characters:
Method | Description |
append(X x) | Appends string representation of x to sequence |
appendCodePoint(int) | Appends Unicode code point |
capacity() | Returns current capacity |
charAt(int) | Returns char at index |
chars() | Returns stream of chars |
codePointAt(int) | Returns code point at index |
codePointBefore(int) | Returns code point before index |
codePointCount(int, int) | Returns count in text range |
codePoints() | Returns stream of code points |
delete(int, int) | Deletes characters in range |
deleteCharAt(int) | Deletes char at index |
ensureCapacity(int) | Ensures minimum capacity |
getChars(int, int, char[], int) | Copies chars into array |
indexOf() | Returns index of substring/char |
insert(int, boolean) | Inserts value at offset |
insert(int, String) | Inserts string at offset |
lastIndexOf() | Returns last index of substring/char |
length() | Returns length |
offsetByCodePoints(int, int) | Returns offset index |
replace(int, int, String) | Replaces substring |
reverse() | Reverses sequence |
setCharAt(int, char) | Sets char at index |
setLength(int) | Sets length |
subSequence(int, int) | Returns subsequence |
substring(int) | Returns substring |
toString() | Converts to String |
trimToSize() | Trims capacity to length |
Example:
The provided example showcases a few of Java’s most commonly used string manipulation methods, demonstrating their practical applications in real-world scenarios.
public class StringMethodsDemo { public static void main(String[] args) { String originalString = "Hello, World!"; // Using the charAt method to retrieve a character at a specific index char charAtIndex3 = originalString.charAt(3); System.out.println("Character at index 3: " + charAtIndex3); // Using the length method to get the length of the string int stringLength = originalString.length(); System.out.println("String length: " + stringLength); // Using the substring method to extract a substring String substring = originalString.substring(7); System.out.println("Substring from index 7: " + substring); // Using the replace method to replace a portion of the string String replacedString = originalString.replace("World", "Java"); System.out.println("Replaced String: " + replacedString); // Using the toString method to convert the string to its string representation String stringRepresentation = originalString.toString(); System.out.println("String representation: " + stringRepresentation); } }
Output:
Character at index 3: 1
String length: 13
Substring from index 7: World!
Replaced String: Hello, Java!
String representation: Hello, World!
Conclusion
In summary, StringBuilder in Java provides an efficient and convenient way to modify strings without creating multiple String objects. Its mutable nature makes it well-suited for scenarios where string manipulation is required frequently. The various methods, such as append, insert, delete, replace, etc., allow easy modification of character sequences.
However, Java StringBuilder lacks synchronization and is not thread-safe. StringBuffer is more appropriate despite being slower for multithreaded environments requiring thread safety. In single-threaded contexts, though, StringBuilder is generally preferred over StringBuffer for performance reasons.
Strings’ immutability provides some advantages in terms of security and concurrency. But when mutability is needed, StringBuilder emerges as the right choice with its mix of efficiency and mutable character sequences. Used judiciously, it enables optimized string handling in Java applications.
Your 15 seconds will encourage us to work even harder
Please share your happy experience on Google