Interview
Strings & Performance — Interview Questions (82+)
See `pkg1core/core9StringsDemo.java` and `pkg19performance`.
Detailed Questions
1. Why are Strings immutable in Java?
- Short: Security, thread-safety, string pool, and cached hashCode.
- Detailed: Immutability lets the string pool share literals safely, allows Strings as stable
HashMapkeys, cacheshashCodeat creation, and prevents mutation via references (class names, network paths). Trade-off: every "change" allocates a new object. - Example:
s.toUpperCase()returns new String;sunchanged.
2. String pool and intern()?
- Short: Pool stores unique literals;
intern()adds heap strings to pool. - Detailed: Literals live in pool (Java 7+ pool in heap).
new String("x")creates heap object;intern()may return pooled reference. Overuse ofintern()on dynamic strings can bloat pool / metaspace. - Example:
"hello" == "hello"true (pooled);new String("hello") == "hello"false.
3. String concatenation performance?
- Short:
+in loop is O(n²); useStringBuilderorString.join. - Detailed: Each
+creates a new String copying prior content. Compiler optimizes constant folding ("a"+"b"→"ab") but not loop concatenation.StringBuilderamortized O(n); thread-safeStringBufferrarely needed. - Example:
for (...) sb.append(x)notresult += x.
4. StringBuilder capacity tuning?
- Short: Set initial capacity if final size known to avoid resize copies.
- Detailed: Default 16 chars; grows by doubling + 2.
new StringBuilder(estimatedSize)reduces array copies.setLength(0)reuses buffer for repeated builds. - Example: Building CSV with known row count × avg length.
5. `String.format` vs `MessageFormat` vs text blocks?
- Short:
formatfor printf-style;MessageFormatfor locale patterns; text blocks for multi-line literals. - Detailed:
"%s %d".formatted(name, age)(Java 15+). Text blocks"""reduce escape noise. For i18n,ResourceBundle+MessageFormat. - Example: See
core9StringsDemoJSON text block.
6. `String` methods added in Java 11+?
- Short:
isBlank,strip,lines,repeat,isEmpty. - Detailed:
stripuses Unicode whitespace (better thantrimfor some chars).lines()returns Stream of lines.repeat(n)for padding/separators. - Example:
" \u2000 ".strip().isBlank()→ true.
7. Charset and encoding gotchas?
- Short: Always specify
Charset(UTF-8); never rely on platform default. - Detailed:
String.getBytes()without charset uses platform encoding — breaks cross-platform.StandardCharsets.UTF_8everywhere. Mojibake from wrong decode. - Example:
s.getBytes(StandardCharsets.UTF_8).
8. `String` vs `char[]` for passwords?
- Short:
char[]can be zeroed after use;Stringstays in pool/heap until GC. - Detailed:
Stringis immutable and may linger in memory dumps.char[]allows explicit wipe. Still not perfect (JIT copies). Prefer secure credential APIs. - Example:
Arrays.fill(password, '\0')after use.
9. Compact Strings (Java 9+)?
- Short: Internal
byte[]+ coder (LATIN1 or UTF16) saves memory for ASCII-heavy strings. - Detailed: Implementation detail but explains memory: many strings use 1 byte/char. Transparent to API.
- Example: Millions of HTTP headers — memory win.
10. Regex performance traps?
- Short: Catastrophic backtracking on nested quantifiers; prefer possessive/atomic or RE2-style libs for untrusted input.
- Detailed:
(a+)+bon longaaaa...can hang.String.matchescompiles pattern each call — cachePattern. UseMatcher.findfor streaming. - Example: Validate email with simple rules or library, not mega-regex.
11. When is `StringBuilder` slower than `+`?
- Short: Few fixed concatenations — compiler may use invokedynamic/string concat factory (Java 9+).
- Detailed:
a + b + cwith known strings is optimized. Loops and dynamic builds still needStringBuilder. - Example: JMH in
pkg19performance/jmh-demo.
12. Microbenchmark pitfalls?
- Short: Warmup JIT, avoid dead-code elimination, use JMH.
- Detailed: Naive
nanoTimeloops lie. Blackholes, forks, multiple JVM forks. Measure allocation with GC logs / JFR. - Example:
StringConcatBenchmarkin pkg19performance.
Rapid-Fire (Q → A)
- String mutable? → No.
- StringBuffer vs Builder? → Buffer synchronized; Builder faster single-thread.
- == on String literals? → Often true (pool).
- new String("a") == "a"? → false.
- equals vs == for Strings? → equals for value.
- hashCode cached? → Yes, after first compute.
- concat method? → Creates new String.
- intern() purpose? → Pool deduplication.
- valueOf(int)? → Converts without
new Stringfor some cases. - toCharArray? → Defensive copy of chars.
- substring (pre-Java 7)? → Shared char array (changed).
- split regex? → Yes; escape
| . *. - split limit param? → Controls array length.
- join delimiter? → String.join or Collectors.joining.
- replace vs replaceAll? → Literal vs regex.
- replaceFirst? → Regex first match.
- indexOf complexity? → O(n×m) naive for pattern.
- contains? → indexOf >= 0.
- startsWith offset? → Overload with index.
- compareTo? → Lexicographic Unicode.
- compareToIgnoreCase? → Case-insensitive.
- isEmpty vs isBlank? → Blank checks whitespace.
- strip vs trim? → strip = Unicode aware.
- lines Stream? → Java 11+.
- repeat? → Java 11+.
- formatted method? → Java 15+ instance format.
- Text blocks? → Java 15+ multi-line.
- Indent on text block? → Normalize leading whitespace.
- translateEscapes? → Unescape \n etc.
- String pool location? → Heap (Java 7+).
- Too many intern()? → Pool pressure.
- in loop problem? → Quadratic copies.
- StringBuilder not thread-safe? → Correct.
- StringBuilder reverse? → In-place.
- ensureCapacity? → Pre-grow buffer.
- setLength? → Shrink logical length.
- charAt bounds? → StringIndexOutOfBounds.
- codePointCount? → Supplementary chars.
- offsetByCodePoints? → Navigate Unicode.
- getBytes UTF-8 size? → Up to 4 bytes per code point.
- new String(bytes, charset)? → Decode bytes.
- Reader vs InputStream text? → Reader char-oriented.
- Scanner delimiter? → Token-based parsing.
- Formatter locale? → Affects numbers/dates.
- MessageFormat placeholders? → {0} {1}.
- ResourceBundle encoding? → UTF-8 in modern JDK properties.
- Collator for sorting? → Locale-sensitive string order.
- Normalizer NFC? → Canonical composition Unicode.
- Performance: avoid regex in hot path? → Often yes.
- Pattern.compile cache? → Reuse compiled Pattern.
- Matcher reset? → Reuse on same Pattern.
- StringBuilder initial 16? → Default capacity.
- AbstractStringBuilder? → Shared by Builder/Buffer.
- Compact strings benefit? → Memory for Latin-1.
- JMH why? → Reliable microbenchmarks.
- Allocation rate metric? → Bytes/sec allocated.
- TLAB? → Thread-local allocation buffer.
- Escape analysis? → Stack allocate short-lived objects.
- Scalar replacement? → Fields on stack if not escaped.
- Profiling first rule? → Measure don't guess.
- JFR? → JDK Flight Recorder low overhead.
- async-profiler? → CPU/allocation flame graphs.
- GC logs for alloc? →
-Xlog:gc*. - String deduplication G1? → Optional same char[] sharing.
- Object overhead? → Header + alignment (~16 bytes min).
- char size? → 2 bytes (UTF-16 code unit).
- Boolean in String.valueOf? → "true"/"false".
- null + string concat? → "null" literal.
- String.valueOf null? → "null".
- concat with null reference? → NPE if reference null on instance concat.
Source named in this chapter
- core9StringsDemopkg1core/core9StringsDemo.java