Strings · Lesson 16 of 42
StringBuilder and String Programs
Because strings are immutable, building text piece by piece with + in a loop creates a new string on every pass. For a handful of pieces that's fine; for thousands it is slow and wastes memory. StringBuilder is the mutable alternative – and string problems built on it are the most common category in Java coding rounds.
In this lesson
- Why
+in a loop is slow StringBuildermethods: append, insert, delete, reverse- String vs StringBuilder vs StringBuffer
- Five string programs every candidate should know
The problem with + in a loop
public class Main {
public static void main(String[] args) {
long t0 = System.nanoTime();
String s = "";
for (int i = 0; i < 20000; i++) s += "x"; // new String each time
long t1 = System.nanoTime();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 20000; i++) sb.append("x"); // same buffer
String built = sb.toString();
long t2 = System.nanoTime();
System.out.println(s.length() == built.length());
System.out.println("StringBuilder faster: " + ((t2 - t1) < (t1 - t0)));
}
}
true StringBuilder faster: true
With +=, every pass copies the whole string so far into a new object – the work grows with the square of the length. StringBuilder appends into a growable buffer instead.
StringBuilder methods
public class Main {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Java");
sb.append(" is").append(" fun"); // chaining
System.out.println(sb);
sb.insert(0, "Learning ");
System.out.println(sb);
sb.replace(0, 8, "Coding");
System.out.println(sb);
sb.delete(sb.length() - 4, sb.length());
System.out.println(sb + "| length " + sb.length());
sb.setCharAt(0, 'c');
System.out.println(sb.reverse());
}
}
Java is fun Learning Java is fun Coding Java is fun Coding Java is| length 14 si avaJ gnidoc
String vs StringBuilder vs StringBuffer
| String | StringBuilder | StringBuffer | |
|---|---|---|---|
| Mutable? | No | Yes | Yes |
| Thread-safe? | Yes (immutable) | No | Yes (synchronized methods) |
| Speed | Slow for repeated changes | Fastest | Slower than StringBuilder |
| Use when | Values that don't change, keys, constants | Building text in one thread (almost always) | Legacy code shared between threads |
Interview angle
Simple concatenation like "Hi " + name + "!" in one expression is fine – the compiler optimises it. The rule is: use StringBuilder when you build a string in a loop.
Five string programs to know
1. Reverse a string and each word
public class Main {
public static void main(String[] args) {
String s = "Java makes placements easier";
System.out.println(new StringBuilder(s).reverse());
String[] words = s.split(" ");
StringBuilder out = new StringBuilder();
for (int i = words.length - 1; i >= 0; i--) {
out.append(words[i]);
if (i > 0) out.append(' ');
}
System.out.println(out);
}
}
reisae stnemecalp sekam avaJ easier placements makes Java
2. Anagram check
import java.util.Arrays;
public class Main {
static boolean isAnagram(String a, String b) {
char[] x = a.replace(" ", "").toLowerCase().toCharArray();
char[] y = b.replace(" ", "").toLowerCase().toCharArray();
Arrays.sort(x);
Arrays.sort(y);
return Arrays.equals(x, y);
}
public static void main(String[] args) {
System.out.println(isAnagram("Listen", "Silent"));
System.out.println(isAnagram("Dormitory", "Dirty room"));
System.out.println(isAnagram("Java", "Lava"));
}
}
true true false
3. Character frequency
import java.util.LinkedHashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Map<Character, Integer> freq = new LinkedHashMap<>();
for (char c : "programming".toCharArray()) {
freq.merge(c, 1, Integer::sum);
}
System.out.println(freq);
}
}
{p=1, r=2, o=1, g=2, a=1, m=2, i=1, n=1}4. First non-repeating character
public class Main {
public static void main(String[] args) {
String s = "swiss";
int[] count = new int[256];
for (char c : s.toCharArray()) count[c]++;
char answer = '-';
for (char c : s.toCharArray()) {
if (count[c] == 1) { answer = c; break; }
}
System.out.println(answer);
}
}
w
5. Compress repeated characters
public class Main {
static String compress(String s) {
StringBuilder sb = new StringBuilder();
int i = 0;
while (i < s.length()) {
char c = s.charAt(i);
int run = 0;
while (i < s.length() && s.charAt(i) == c) { i++; run++; }
sb.append(c).append(run);
}
return sb.length() < s.length() ? sb.toString() : s;
}
public static void main(String[] args) {
System.out.println(compress("aaabbcccca"));
System.out.println(compress("abc"));
}
}
a3b2c4a1 abc
Practice
Try it yourself
Capitalise the first letter of every word in "learn java with frenzy".
Show solution
public class Main { public static void main(String[] args) { StringBuilder sb = new StringBuilder(); for (String w : "learn java with frenzy".split(" ")) { sb.append(Character.toUpperCase(w.charAt(0))).append(w.substring(1)).append(' '); } System.out.println(sb.toString().trim()); } }Learn Java With Frenzy
Remove duplicate characters from "programming", keeping the first occurrence.
Show solution
public class Main { public static void main(String[] args) { StringBuilder sb = new StringBuilder(); for (char c : "programming".toCharArray()) { if (sb.indexOf(String.valueOf(c)) == -1) sb.append(c); } System.out.println(sb); } }progamin
Quick check
Why use StringBuilder in a loop?
It appends into one mutable buffer instead of creating a new String on every pass.
Which is thread-safe: StringBuilder or StringBuffer?
StringBuffer (its methods are synchronized). StringBuilder is faster but not thread-safe.
How do you reverse a String in one line?
new StringBuilder(s).reverse().toString()
Summary
- Use
StringBuilderto build strings in loops;StringBufferonly for shared legacy code. - append, insert, replace, delete, reverse all change the builder in place.
- Reversal, anagrams, frequency, first unique char and compression cover most string questions.
Interview practice: Java strings, exceptions and generics.
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.