C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Part 1: We create a StringBuilder. Then we use a for-loop and append 5 strings to the StringBuilder.
ForPart 2: We convert the data into a String object. We display the resulting String to the Console with the System.out.println method.
StringsJava program that uses StringBuilder
import java.lang.StringBuilder;
public class Program {
public static void main(String[] args) {
// Part 1: create a new StringBuilder.
StringBuilder builder = new StringBuilder();
// ... Loop and append values.
for (int i = 0; i < 5; i++) {
builder.append("abc ");
}
// Part 2: convert to string.
String result = builder.toString();
// ... Print result.
System.out.println(result);
}
}
Output
abc abc abc abc abc
Part A: We call append() on the result of a previous append() call. Append returns the original StringBuilder.
Part B: We get a String instance from the StringBuilder with toString(), and write the String to the screen.
Java program that appends values
import java.lang.StringBuilder;
public class Program {
public static void main(String[] args) {
int value1 = 300;
double value2 = 3.14;
short value3 = 5;
char value4 = 'A';
// Part A: create StringBuilder and add 4 values to it.
StringBuilder builder = new StringBuilder();
builder.append(value1).append("\n");
builder.append(value2).append("\n");
builder.append(value3).append("\n");
builder.append(value4);
// Part B: display results.
String result = builder.toString();
System.out.println(result);
}
}
Output
300
3.14
5
A
Index: This is the first argument. To insert after the second character, use the value 2. And to insert at the start, use zero.
String: We pass a string (or other value) as the second argument. This is the data that is placed into the StringBuilder.
Java program that uses insert
import java.lang.StringBuilder;
public class Program {
public static void main(String[] args) {
// Initialize StringBuilder with this value.
StringBuilder builder = new StringBuilder("abc");
// Insert this substring at position 2.
builder.insert(2, "xyz");
System.out.println(builder);
}
}
Output
abxyzc
Found: If the substring is found within the StringBuilder, the first index where it occurs is returned as an int.
Not found: If no matching substring is found, the special value negative one is returned. We must often check for -1 when using indexOf.
Java program that uses indexOf
import java.lang.StringBuilder;
public class Program {
public static void main(String[] args) {
StringBuilder builder = new StringBuilder("abc");
// Try to find this substring.
int result = builder.indexOf("bc");
System.out.println(result);
// This substring does not exist.
int result2 = builder.indexOf("de");
System.out.println(result2);
}
}
Output
1
-1
Java program that uses delete
import java.lang.StringBuilder;
public class Program {
public static void main(String[] args) {
StringBuilder builder = new StringBuilder("carrot");
// Delete characters from index 2 to index 5.
builder.delete(2, 5);
System.out.println(builder);
}
}
Output
cat
Java program that uses replace method
import java.lang.StringBuilder;
public class Program {
public static void main(String[] args) {
// Create new StringBuilder.
StringBuilder b = new StringBuilder("abc");
// Replace second character with "xyz".
b.replace(1, 2, "xyz");
System.out.println(b);
}
}
Output
axyzc
Java program that combines StringBuilders
public class Program {
public static void main(String[] args) {
StringBuilder builder = new StringBuilder("cat");
StringBuilder builder2 = new StringBuilder("dog");
// Combine 2 StringBuilders.
builder.append(builder2);
System.out.println(builder);
}
}
Output
catdog
Arguments: The first argument is the start index of the desired substring. The second argument is last index (not the character count).
Java program that uses substring
import java.lang.StringBuilder;
public class Program {
public static void main(String[] args) {
StringBuilder builder = new StringBuilder();
builder.append("Forest");
// Get substring after the first 2 characters.
String omitFirstTwo = builder.substring(2);
System.out.println(omitFirstTwo);
// Get only the first 2 characters in a substring.
String firstTwo = builder.substring(0, 2);
System.out.println(firstTwo);
}
}
Output
rest
Fo
Length: This method returns the count of characters in the StringBuilder. The highest index is the count of chars minus one.
CharAt: This accesses a character within the StringBuilder. We can use it anywhere, not just in a for-loop.
Java program that loops over StringBuilder chars
import java.lang.StringBuilder;
public class Program {
public static void main(String[] args) {
StringBuilder builder = new StringBuilder("magic");
// Loop over the characters in this StringBuilder.
for (int i = 0; i < builder.length(); i++) {
System.out.println(builder.charAt(i));
}
}
}
Output
m
a
g
i
c
Java program that uses setLength method
import java.lang.StringBuilder;
public class Program {
public static void main(String[] args) {
StringBuilder builder = new StringBuilder("carrot");
// Use setLength to remove characters from the end.
builder.setLength(3);
System.out.println(builder);
}
}
Output
car
Java program that uses capacity
import java.lang.StringBuilder;
public class Program {
public static void main(String[] args) {
// Use a 100-char capacity.
StringBuilder temp = new StringBuilder(100);
// Add 100 characters to the StringBuilder.
// ... Theoretically this is faster.
for (int i = 0; i < 25; i++) {
temp.append("1234");
}
System.out.println(temp.length());
}
}
Output
100
Java program that uses reverse
import java.lang.StringBuilder;
public class Program {
public static void main(String[] args) {
// A StringBuilder can be reversed.
StringBuilder builder = new StringBuilder();
builder.append("abc");
builder.reverse();
System.out.println(builder);
}
}
Output
cba
Version 1: This version of the code adds 10,000 numbers (and spaces) to a string. We use the string concatenation operator.
Version 2: Here we perform many appends on a StringBuilder. The StringBuilder does not have a capacity set.
Result: The String adds require significant time (251 ms) while the StringBuilder appends require less than 1 ms.
Java program that times String, StringBuilder
import java.lang.StringBuilder;
public class Program {
public static void main(String[] args) {
long t1 = System.currentTimeMillis();
// Version 1: add to string.
String value = "";
for (int i = 0; i < 10000; i++) {
value += Integer.toString(i) + ' ';
}
long t2 = System.currentTimeMillis();
// Version 2: append to StringBuilder.
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 10000; i++) {
builder.append(i).append(' ');
}
long t3 = System.currentTimeMillis();
// ... Lengths are equal.
System.out.println(value.length());
System.out.println(builder.length());
// ... Times.
System.out.println(t2 - t1);
System.out.println(t3 - t2);
}
}
Output
48890
48890
251 ms, String + operator (20000 adds)
0 ms, StringBuilder append (20000 calls)
Version 1: In this test, the StringBuilder grows to a size of one million chars with no capacity set.
Version 2: The second StringBuilder meanwhile uses an exact capacity of 1,000,000. The two are benchmarked.
Result: The exact capacity makes the second StringBuilder nearly twice as fast to complete its meaningless task.
Java program that benchmarks capacity use
import java.lang.StringBuilder;
public class Program {
public static void main(String[] args) {
long t1 = System.currentTimeMillis();
// Version 1: does not use capacity.
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 1000000; i++) {
builder.append(' ');
}
long t2 = System.currentTimeMillis();
// Version 2: uses exact capacity.
StringBuilder builder2 = new StringBuilder(1000000);
for (int i = 0; i < 1000000; i++) {
builder2.append(' ');
}
long t3 = System.currentTimeMillis();
// ... Times.
System.out.println(t2 - t1);
System.out.println(t3 - t2);
}
}
Output
10 ms, no capacity
6 ms, exact capacity
Version 1: This version of the code appends a one-character String literal in a tight loop, repeated many times.
Version 2: Here we do not append a string, but instead append a single character—a character literal.
Result: It is faster to use a char argument to append() than a String argument. I have found this helps many programs.
Java program that times String, char appends
import java.lang.StringBuilder;
public class Program {
public static void main(String[] args) {
long t1 = System.currentTimeMillis();
// Version 1: appends one-char strings.
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 1000000; i++) {
builder.append("X");
}
long t2 = System.currentTimeMillis();
// Version 2: appends chars directly.
StringBuilder builder2 = new StringBuilder();
for (int i = 0; i < 1000000; i++) {
builder2.append('X');
}
long t3 = System.currentTimeMillis();
// ... Times.
System.out.println(t2 - t1);
System.out.println(t3 - t2);
}
}
Output
15 ms, append() String argument
7 ms, append() char argument