Beginner⏱️ 10 min📘 Topic 8 of 22

🔤 Java Strings — String, StringBuilder and Immutability

Master Java Strings — immutability, the String pool, == vs equals, StringBuilder vs StringBuffer, common methods and performance. With examples and interview questions.

String is the most-used class in Java — and a top interview topic because of immutability.

🔒 Strings are immutable

Once created, a String's characters never change. Every 'modifying' method (concat, replace, toUpperCase) returns a new String. Immutability makes Strings thread-safe, cacheable and safe as map keys.

🏊 The String pool

String literals are interned in a special heap region (the pool). Two identical literals share one object:

String a = "hi";
String b = "hi";      // same pooled object
String c = new String("hi"); // NEW object on heap
a == b;        // true  (same pool reference)
a == c;        // false (different objects)
a.equals(c);   // true  (same content)

🏗️ StringBuilder vs StringBuffer

Building strings in a loop with + creates a new String each iteration — O(n²). Use a mutable builder:

  • StringBuilder — fast, NOT thread-safe. Default choice.
  • StringBuffer — synchronized (thread-safe), slower. Rarely needed.

🔧 Must-know methods

length(), charAt(i), substring(a, b), indexOf, contains, split, trim/strip, replace, format. Need to format or inspect JSON strings while debugging? Our JSON Formatter tool pairs well here.

💻 Code Examples

== vs equals

String a = "java";
String b = new String("java");
System.out.println(a == b);       // false
System.out.println(a.equals(b));  // true
Output:
false
true

StringBuilder in a loop (efficient)

StringBuilder sb = new StringBuilder();
for (int i = 0; i < 3; i++) sb.append(i).append(",");
System.out.println(sb.toString());
Output:
0,1,2,

Useful methods

String s = "  Hello, World  ";
System.out.println(s.strip());
System.out.println(s.strip().toUpperCase());
System.out.println("a,b,c".split(",").length);
Output:
Hello, World
HELLO, WORLD
3

⚠️ Common Mistakes

  • Comparing Strings with == instead of .equals() — == checks reference identity, not content.
  • Concatenating Strings in a loop with + — creates many temporary objects; use StringBuilder.
  • Forgetting Strings are immutable — `s.replace(...)` returns a new String, it doesn't change s.
  • Using StringBuffer by default — you rarely need its synchronization; StringBuilder is faster.

🎯 Interview Questions

Real questions asked at top product and service-based companies.

Q1.Why are Strings immutable in Java?Beginner
Immutability gives thread safety (shareable without locks), allows the String pool to cache and reuse literals, makes Strings safe as HashMap keys (hashcode won't change), and improves security (e.g., file paths can't be altered after a check).
Q2.What is the String pool?Intermediate
A cache in the heap where String literals are interned. Identical literals reference the same object, saving memory. new String() bypasses the pool and creates a distinct object; .intern() puts it back in the pool.
Q3.Difference between == and equals() for Strings?Beginner
== compares object references (are they the same object?). equals() compares the actual character sequence. For content comparison, always use equals().
Q4.StringBuilder vs StringBuffer — when to use which?Intermediate
Both are mutable string builders. StringBuilder is not synchronized and faster — use it by default. StringBuffer is synchronized (thread-safe) but slower — only needed when multiple threads append to the same buffer, which is rare.
Q5.What's the time complexity of building a String with + in a loop?Advanced
O(n²) — each concatenation copies the entire accumulated string into a new object. StringBuilder amortizes to O(n) by mutating an internal char array.

🧠 Quick Summary

  • String is immutable — methods return new Strings.
  • Literals are interned in the String pool; new String() isn't.
  • Compare content with .equals(), not ==.
  • Use StringBuilder for loops; StringBuffer only when thread-safe.
  • Concatenation with + in a loop is O(n²).