🔤 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)); // truefalse 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());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);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
Q2.What is the String pool?Intermediate
Q3.Difference between == and equals() for Strings?Beginner
Q4.StringBuilder vs StringBuffer — when to use which?Intermediate
Q5.What's the time complexity of building a String with + in a loop?Advanced
🧠 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²).