String is immutable
Once created, a String never changes. Methods like toUpperCase() or concat() return a new string; the original stays as it was.
String s = "java";s.toUpperCase(); // result thrown awaySystem.out.println(s); // javas = s.toUpperCase(); // s now points at a new object "JAVA"
- Security: strings are used for file paths, URLs and class names; nobody can change one after it was checked.
- Thread safety: immutable objects can be shared between threads without locks.
- Caching: the hash code is computed once and cached, which makes strings fast
HashMapkeys. - String pool: sharing literals is only safe because they can't change.
The string pool
String literals are stored once in the string pool (part of the heap since Java 7). Two literals with the same text refer to the same object. new String("x") always creates a separate object. intern() returns the pooled copy.
String a = "hello";String b = "hello";String c = new String("hello");a == b; // true: same pooled objecta == c; // false: c is a separate objecta.equals(c); // true: same charactersa == c.intern(); // true
Always compare strings with equals(). == only tells you whether two references point at the same object.
StringBuilder and StringBuffer
Building a string with += in a loop creates a new string each time and copies all characters so far: O(n²) for n pieces. StringBuilder keeps a growable character array and appends in amortized O(1), like a dynamic array.
StringBuilder sb = new StringBuilder();for (int i = 0; i < 5; i++) sb.append(i).append(',');sb.setLength(sb.length() - 1); // drop the last commaString result = sb.toString(); // "0,1,2,3,4"
| String | StringBuilder | StringBuffer | |
|---|---|---|---|
| Mutable | No | Yes | Yes |
| Thread-safe | Yes (immutable) | No | Yes (synchronized) |
| Speed | Slow for repeated edits | Fastest | Slower than StringBuilder |
Stack vs heap
Each thread has its own stack of frames: one per method call, holding parameters, local primitives and references. Objects (including arrays and strings) live on the shared heap. When a method returns its frame is popped; heap objects stay until no references reach them, then the garbage collector frees them.
- Too-deep recursion fills the stack:
StackOverflowError. - Too many live objects fill the heap:
OutOfMemoryError. - Primitives inside objects (fields) live on the heap with the object.
Primitives, wrappers and autoboxing
Each primitive has a wrapper class (int → Integer). Collections hold objects only, so Java converts automatically: autoboxing (int → Integer) and unboxing back.
Integer a = 127, b = 127;a == b; // true: values -128..127 are cachedInteger c = 128, d = 128;c == d; // false: different objectsc.equals(d); // trueInteger n = null;int x = n; // NullPointerException while unboxing
See it animated
Interview questions
Try answering out loud first, then open the model answer.
Q1Why is String immutable in Java?beginner
For security (strings hold paths, URLs and class names that must not change after validation), thread safety without locks, a cached hash code for fast map keys, and to make sharing literals in the string pool safe.
Q2What's the difference between == and equals() for strings?beginner
== checks whether two references point at the same object; equals() checks whether the characters are the same. Two equal strings can be different objects (e.g. one from new String() or built at run time), so use equals().
Q3How many objects does new String("abc") create?intermediate
Up to two: the literal "abc" in the string pool (only if it isn't there already, at class load) and one new String object on the heap from new.
Q4When would you use StringBuilder over String concatenation?beginner
When building a string in a loop or in many steps. Each + on a String creates a new object and copies characters, which is O(n²) overall; StringBuilder appends into one growable buffer. (The compiler already uses a builder for a single expression like a + b + c.)
Q5StringBuilder vs StringBuffer?beginner
Same API. StringBuffer's methods are synchronized, so it's thread-safe but slower. StringBuilder isn't synchronized; prefer it, since builders are almost always local to one thread.
Q6Why does Integer a = 128, b = 128; a == b print false but 127 prints true?intermediate
Autoboxing uses Integer.valueOf(), which caches values from -128 to 127. Inside that range both variables get the same cached object; outside it each boxing creates a new object, so == compares two different references. Use equals() for wrappers.
Q7What is stored on the stack and what on the heap?beginner
The stack holds a frame per method call: local primitives and references. The heap holds all objects and arrays, including their fields. Stacks are per-thread; the heap is shared by all threads and managed by the garbage collector.
Quick check
0 of 4 answered