Strings in Java
A String is an immutable sequence of characters. "Immutable" here is not a detail but the foundation: a string's contents are fixed at construction and never change, and any method that looks like a modification (toUpperCase, trim, replace, concat) returns a new object, leaving the original untouched. Almost everything asked about strings grows from this one property.
Immutability makes it safe to share one object among many holders — that is what the string pool is built on, where identical literals share a single object and new String(...) deliberately creates a separate one. It also makes a string a reliable hash-map key and thread-safe without synchronization. And when a string genuinely needs to be assembled piece by piece, the mutable builders — StringBuilder and StringBuffer — step in, because concatenating immutable strings in a loop costs O(n²). The full map is in the layers below.
Topic map
- String Immutability — contents never change, "modifying" methods return a new object, and what that buys you.
- The String Pool — the shared cache of literals,
==vsequals,new String()andintern(). - StringBuilder vs StringBuffer — mutable builders, why
+in a loop is O(n²), and which one is synchronized.
Common traps
| Mistake | Consequence |
|---|---|
Thinking replace/trim/concat modify the string in place | The original never changes; the result is lost unless you assign it |
Comparing strings with == | It compares references, not values — new String("x") == "x" is false |
Assuming new String("x") and the literal "x" are one object | They are distinct objects; == is false, equals is true |
Believing intern() happens automatically for every string | Only literals are pooled by default; dynamic strings must be interned explicitly |
Building text by + concatenation in a loop | Each iteration allocates a new String and copies everything — O(n²) instead of O(n) |
Assuming StringBuilder is thread-safe | It is unsynchronized; sharing one instance across threads corrupts it |
Interview relevance
Strings come up on almost every Java interview, but the check is not method recall — it is the consequences of immutability: why you compare with equals, why the pool exists, and when to reach for a builder instead of +.
Typical checks:
- That
Stringis immutable and exactly what that buys you (pool, keys, thread-safety). - How the string pool works and how a literal differs from
new String(). - What
intern()does. - Why
+in a loop is O(n²) and howStringBuilderfixes it. - The difference between
StringBuilderandStringBufferin synchronization.
Common wrong answer: "you should compare strings with == when they are equal." That opens the discussion that == checks object identity, not value equality: two equal literals match because of the pool, but new String("x") gives false — so for value equality you always compare with equals.