What is StringBuilder class?
The StringBuilder class can be used to create mutable strings. The methods defined in the StringBuilder class are widely used to manipulate and concatenate strings. It is a non-synchronized class which has public methods that can be accessed by multiple threads. It is not thread-safe.
An object created by instantiating the StringBuilder class is known as the StringBuilder object.
StringBuilder class in Java
In the Java programming language, the StringBuilder class is used to create strings which can be modified later. It was first developed for the Java 1.5 version. The class is available in the java.lang package and is mainly used in single-threaded environments to manipulate object of type String. The StringBuilder class in Java does not guarantee synchronization.
Example of Java code using the Stringbuilder class:
import java.lang.*;
public class StringBuilderDemo{
public static void main(String args[]){
StringBuilder sb1 = new StringBuilder(“Hello”);
sb1.append(“ World”);
System.out.println(sb1);
}
}
Output:
Hello World
Explanation:
The string "Hi" is created by instantiating the StringBuilder class. Then, the append() method is invoked for appending the string " World" so that the string "Hello World" is displayed on the console.
Common methods available in the Java StringBuilder class are listed below:
- public StringBuilder append(String s)
It is used to append the string passed as input parameter with the string object used for invoking the method. Example: sb1.append("Hello")
- public StringBuilder insert(int offset, String s)
It is used to insert a specific string at the specified position. For example, the method call sb1.insert(1, “Hi”) inserts the string "Hi" in the position 1 of the string sb1.
- public StringBuilder delete(int startIndex, int endIndex)
It is used to delete the substring specified by the positions startIndex and endIndex passed as arguments to the method. For example, the method call sb1.delete(1,3) deletes the three characters in the positions from 1 to 3 in the string sb1.
- public StringBuilder replace(int startIndex, int endIndex, String str)
It is used to the substring specified by the offsets startIndex and endIndes with the string str. For example, the method call sb1.replace(1,2, “Hello”) replaces the characters at position 1 and 2 of the string sb1 with the string "Hello".
- public char charAt(int index)
It is used to return the character present at the position specified by index. For example: sb1.charAt(1);
- public StringBuilder appendCodePoint(int codePoint)
It is used to append a code point passed as argument to the string. The integer value of the code point is passed as parameter to the method. Example: sb1.appendCodePoint(67);
- public int codePointBefore(int index)
It returns a character that precedes the given address. The index is passed argument to the method. Example: sb1.codePointBefore(2)
- public int codePointCount(int beginIndex, int endIndex)
It returns the number of Unicode points in the sub array.
Other methods offered by the StringBuilder class are:
public int offsetByCodePoints(int index, int codePointOffset)
public StringBuilder reverse()
public String substring(int start)
public void trimToSize()
StringBuilder class in C#
Like the StringBuilder class in Java, the StringBuilder class in C# creates mutable Strings. In other words, StringBuilder class in C# is used to change the Strings after they are created.
The StringBuilder class creates mutable String objects. StringBuilder methods can be used to modify, remove, append and replace strings.
Below is a list of the common methods in the StringBuilder class of C# language:
1. StringBuilder.Append(String value)
Appending a string to another string can be done using the Append method. Appendline() is a type of method under the Append method. It adds a new line at the end of the appended string. Example: sb.append(“Hi”);
2. StringBuilder.AppendFormat()
The AppendFormat() method is used to append the string after formatting it. Changing the case and spacing of the input string are examples of string formatting. Example: sb1.AppendFormat("{0:C} ", 50)
3. StringBuilder.Insert(int index, String value)
This method inserts a new string at a specific position. It takes two arguments. The position is passed as the first argument and the string to be inserted is passed as the second argument. Example: sb1.insert(1, “Hey”);
4. StringBuilder.Remove(int start, int length)
This method is used to remove a part of the string from the given string. The first argument represents the starting index and the second argument represents the number of characters to be removed. Example: sb1.remove(3, 6);
5. StringBuilder.Replace(old_value, new_value)
It is used to replace the substring which matches with the first argument with the substring represented by the second argument in the given string. Example: sb1.replace(“Hi”, “Hello”);
Constructors used in StringBuilder class
Constructors are used for creating objects under the main class. It is mainly used in object-oriented languages. The name of the constructor must be same as the method of the class.
Some common constructors used in the StringBuilder class are listed below.
Constructor Name | Function |
StringBuilder() | Constructs a StringBuilder with no characters and initial capacity of 16 characters |
StringBuilder(Int capacity) | Constructs a StringBuilder with no characters and initial capacity as defined in the method. For example, StringBuilder(32) will define a String builder with a capacity of 32 characters. |
StringBuilder(String str) | Constructs a StringBuilder initialized to the contents mentioned in the string. |
StringBuilder(CharSequence char) | Constructs a StringBuilder consisting of the characters mentioned in the CharSequence. |
Difference between String class and StringBuilder class
- The main difference between String and StringBuilder classes is that they have different namespaces. System namespace includes String class whereas System.Text namespace includes the StringBuilder class.
- String class creates immutable Strings, contrarily StringBuilder class creates mutable Strings. The StringBuilder class is faster than the String class but the former is not thread-safe.
- For concatenation operations within literals, the String class is preferred over the String builder class. This is because the compiler can perform concatenation activity in a single operation.
- When the size of the operating String is large, using the String builder class can accommodate the most number of changes, but it lacks extensive search options. To search through a String for a particular index, the String class is preferred to the StringBuilder class.
Memory usage of StringBuilder object
A StringBuilder object created using the StringBuilder class has a capacity of 16 characters by default. The maximum capacity is achieved by Int32.MaxValue.
The storing capacity of a StringBuilder object can be defined using particular constructors. Some constructors in the StringBuilder class include an attribute that specifies the capacity of the StringBuilder object that can be created using it. By changing the value of this attribute, one can change the default value of the StringBuilder object's capacity.
Capacity is the method used to increase the current capacity of an existing object. The new capacity should be less than the maximum possible capacity under the class and should be greater than the existing capacity. Failure to meet these conditions leads to an error during compilation.
Context and Applications
Object-oriented programming languages are globally used for web page development and application interface development. StringBuilder class is an important class in every object-oriented programming language, so it has a wide range of applications.
- Bachelors in computer science
- Masters in computer science
Practice Problems
Q1. Which of the following classes are used to create mutable Strings?
- String()
- StringBuilder()
- String args [int index]
- MinimumCapacity new StringBuilder insert
Answer- Option b
Explanation- The String class creates immutable Strings whereas the StringBuilder class is used to create mutable Strings.
Q2. Which package contains the StringBuilder class?
- java.awt
- new StringBuilderExample
- java.lang
- public static void
Answer- Option c
Explanation- The StringBuilder class is imported from java.lang package. So, the java.lang package contains the StringBuilder class.
Q3. Which of the following is used to append a StringBuilder object?
- CodePointAt
- Cout
- getChars CharSequence s
- append()
Answer- Option d
Explanation- public StringBuilder append() is an inbuilt method in the StringBuilder class to append objects.
Q4. Which of the following is not a StringBuilder method in a Java program?
- Java.util.dstOffset
- delete()
- appendCodePoint()
- codePointBefore()
Answer- Option a
Explanation- delete(), appendCodePoint(), and codePointBefore() are methods in Java StringBuilder. However, Java.util.dstOffset is used to set the date and time, the zone is given as the input parameter. It is not under the String builder class.
Q5. Which of the following is the function of codePointCount?
- To create int index multi-threading classes
- To create ensure capacity Strings
- To get the Unicode code point of the String
- Returns the number of Unicode points within the specified range
Answer- Option d
Explanation- The codePointCount method in the StringBuilder class returns count of Unicode points within the specified range.
Common Mistakes
String object created using String class is different from StringBuilder object. The string referenced by StringBuilder object can be modified by using the methods associated with the StringBuilder class.
Related Concepts
- java.lang package
- Strings in Java
- StringBuilder in C#
Want more help with your computer science homework?
*Response times may vary by subject and question complexity. Median response time is 34 minutes for paid subscribers and may be longer for promotional offers.
Search. Solve. Succeed!
Study smarter access to millions of step-by step textbook solutions, our Q&A library, and AI powered Math Solver. Plus, you get 30 questions to ask an expert each month.
Methods of StringBuilder class Homework Questions from Fellow Students
Browse our recently answered Methods of StringBuilder class homework questions.
Search. Solve. Succeed!
Study smarter access to millions of step-by step textbook solutions, our Q&A library, and AI powered Math Solver. Plus, you get 30 questions to ask an expert each month.