Senior 5 min · March 05, 2026

Java String Immutability Stops TOCTOU Exploits

Heavy-load security flaws from mutable StringBuilder? Immutability prevents TOCTOU.

N
Naren · Founder
Plain-English first. Then code. Then the interview question.
About
 ● Production Incident 🔎 Debug Guide
Quick Answer
  • String objects are immutable: content never changes after creation
  • Variables are mutable: you can re-point them to a new String object
  • String Pool caches literals safely only because Strings can't change
  • Concatenation in a loop creates O(n) objects — use StringBuilder for loop assembly
  • Immutability enables thread safety without locks and cached hash codes
  • Biggest mistake: using == instead of .equals() for value comparison
Plain-English First

Imagine you carve your name into a wooden block. If someone wants to write your nickname instead, they can't erase it — they have to carve a brand new block. That's exactly how Java Strings work. Once a String is created, it's locked. Any 'change' you make actually produces a brand new String object behind the scenes, leaving the original untouched. The old block still exists in memory until no one needs it anymore.

Every Java developer has written String code from day one, but most don't realise they're working with one of the most carefully designed classes in the entire language. String immutability isn't an accident or a limitation — it's a deliberate architectural decision that affects performance, security, thread safety, and memory management all at once. Ignoring WHY it works this way is how developers write code that silently destroys performance in loops or introduces subtle security holes in web apps.

The problem immutability solves is surprisingly deep. Without it, a String passed into a security-sensitive method — say, a database connection URL or a file path — could be mutated by another thread or a misbehaving library between the moment you validated it and the moment you used it. The JVM's String Pool, which caches and reuses String literals to save memory, would also be completely unsafe if two pieces of code could change the same shared object. Immutability is the foundation that makes all of this safe.

By the end of this article you'll understand exactly what happens in memory when you concatenate Strings in a loop, why StringBuilder exists and when you must reach for it, how the String Pool and the intern() method work under the hood, and what the tricky interview questions about String identity (==) versus equality (.equals()) are really testing. You'll write faster, safer, more confident Java from here on.

What Immutability Actually Means in Memory

When you write String name = "Alice", the JVM creates a String object in a special region of the heap called the String Pool (more on that shortly) and points the variable name at it. Now when you write name = name + " Smith", it looks like you changed name. You didn't. The JVM created a brand new String object "Alice Smith" and re-pointed the variable at it. The original "Alice" is still sitting in memory, unchanged.

This is the single most important thing to internalise: the variable is mutable (you can re-point it), but the object it points to is immutable (the content never changes).

Under the hood, a String is backed by a private final char[] (or byte[] in modern Java). The field is final so it can't be re-assigned, and it's private so no external code can reach in and change the array's contents. The class itself is also declared final, so nobody can subclass it and override that protection. These three decisions — private, final field, final class — work together to make immutability airtight.

StringMemoryDemo.javaJAVA
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class StringMemoryDemo {
    public static void main(String[] args) {

        // A String literal — JVM places "Alice" in the String Pool
        String firstName = "Alice";

        // Capture the identity hash code — a proxy for memory address
        int originalIdentity = System.identityHashCode(firstName);
        System.out.println("Original object id : " + originalIdentity);
        System.out.println("Original value     : " + firstName);

        // This looks like a modification — it is NOT
        // Java creates a NEW String object and re-points firstName at it
        firstName = firstName + " Smith";

        int newIdentity = System.identityHashCode(firstName);
        System.out.println("\nNew object id      : " + newIdentity);
        System.out.println("New value          : " + firstName);

        // Prove the two ids are different — they are different objects
        System.out.println("\nSame object?       : " + (originalIdentity == newIdentity));
    }
}
Output
Original object id : 1975012498
Original value : Alice
New object id : 1808253012
New value : Alice Smith
Same object? : false
Why This Matters:
Every concatenation inside a loop allocates a new object. Five concatenations on a 1,000-iteration loop = 1,000 short-lived objects the GC must clean up. This is why StringBuilder exists — more on that in the next section.
Production Insight
The identityHashCode trick works only because Strings are immutable — hash code is cached, not recomputed.
If you see high GC pressure with many char[] allocations, profile your string code.
Rule: every = operator on a String creates a new object — count them in your loops.
Key Takeaway
String variables are mutable references, not immutable containers.
The object behind a variable never changes — only the pointer does.
Immutability is enforced by the class design, not by your code.

The String Pool — How Java Recycles String Objects

The String Pool (officially the 'string intern pool') is a cache inside the heap. When the JVM sees a string literal like "hello", it checks the pool first. If "hello" is already there, it hands back the existing reference rather than creating a new object. This is safe only because Strings are immutable — if they weren't, sharing references would be a disaster.

Strings created with new String("hello") deliberately bypass the pool and always create a fresh heap object. This is almost never what you want, and it's the source of the classic == trap.

The intern() method lets you manually push a String into the pool. This is useful when you're building a huge dataset with many repeated strings (like parsing CSV column names thousands of times) and you want to collapse duplicates. From Java 7 onwards, the pool lives on the regular heap (not PermGen), so it's subject to normal garbage collection — a big improvement.

StringPoolDemo.javaJAVA
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class StringPoolDemo {
    public static void main(String[] args) {

        // Both literals point to the SAME pooled object
        String pooledA = "java";
        String pooledB = "java";

        // new String() forces a brand-new heap object, bypassing the pool
        String heapString = new String("java");

        // intern() pushes heapString into the pool (or returns the existing entry)
        String internedString = heapString.intern();

        System.out.println("--- Reference Equality (==) ---");
        // true  — both point to the same pool object
        System.out.println("pooledA == pooledB         : " + (pooledA == pooledB));
        // false — heapString is a separate heap object
        System.out.println("pooledA == heapString      : " + (pooledA == heapString));
        // true  — intern() returned the existing pool entry
        System.out.println("pooledA == internedString  : " + (pooledA == internedString));

        System.out.println("\n--- Value Equality (.equals()) ---");
        // Always true for same content — this is what you should use in production
        System.out.println("pooledA.equals(heapString) : " + pooledA.equals(heapString));
    }
}
Output
--- Reference Equality (==) ---
pooledA == pooledB : true
pooledA == heapString : false
pooledA == internedString : true
--- Value Equality (.equals()) ---
pooledA.equals(heapString) : true
Watch Out:
Never use == to compare String values in production code. It compares memory addresses, not content. Two Strings with identical text will return false if one came from new String() or from an external source like a database or network. Always use .equals() or .equalsIgnoreCase().
Production Insight
The String Pool is a classic space-for-time trade-off: memory saved by reusing literals vs lookup cost.
Internally, the pool is implemented as a fixed-size hash table — too many unique strings degrade lookup performance.
Rule: only intern strings with high repetition; never intern user-generated data at scale.
Key Takeaway
String literals are automatically pooled — new String() creates a separate object.
The pool relies on immutability for safety.
Use intern() sparingly: it's a tool for large datasets with many duplicate strings.

When Immutability Hurts — String vs StringBuilder vs StringBuffer

Immutability is a gift for safety but a curse for heavy modification. If you're building a String piece by piece — assembling SQL fragments, constructing a CSV row, building HTML — creating a new object on every step is wasteful. This is exactly why StringBuilder was introduced.

StringBuilder is a mutable sequence of characters. It pre-allocates a buffer and appends into it in-place. No new object per operation. When you're done, you call .toString() once to produce the final immutable String.

StringBuffer is the older, thread-safe sibling. Every method is synchronized, which makes it safe across threads but slower in single-threaded code. The rule of thumb: use StringBuilder in single-threaded code (the vast majority of cases), reach for StringBuffer only when multiple threads share the same builder — though in modern Java you'd more likely restructure the code to avoid that pattern altogether.

The compiler actually helps you here: simple one-liner concatenations like "Hello, " + name + "!" are auto-compiled to use StringBuilder internally. But the moment that concatenation is inside a loop, the compiler creates a new StringBuilder per iteration, defeating the purpose.

StringBuilderPerformanceDemo.javaJAVA
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public class StringBuilderPerformanceDemo {

    private static final int ITERATIONS = 50_000;

    public static void main(String[] args) {
        System.out.println("Comparing String concatenation vs StringBuilder over "
                + ITERATIONS + " iterations.\n");

        // --- Approach 1: Naive String concatenation in a loop ---
        // Each += creates a NEW String object — ITERATIONS new objects total
        long startNaive = System.currentTimeMillis();
        String naiveResult = "";
        for (int i = 0; i < ITERATIONS; i++) {
            naiveResult += "x"; // new object allocated every single iteration
        }
        long naiveTime = System.currentTimeMillis() - startNaive;
        System.out.println("Naive String concatenation : " + naiveTime + " ms");

        // --- Approach 2: StringBuilder ---
        // One mutable buffer, appended in-place, one final toString() call
        long startSB = System.currentTimeMillis();
        StringBuilder sb = new StringBuilder(ITERATIONS); // pre-size the buffer
        for (int i = 0; i < ITERATIONS; i++) {
            sb.append("x"); // mutates the buffer — no new object
        }
        String sbResult = sb.toString(); // ONE allocation at the end
        long sbTime = System.currentTimeMillis() - startSB;
        System.out.println("StringBuilder              : " + sbTime + " ms");

        // Sanity check — both approaches produce the same final content
        System.out.println("\nResults match              : " + naiveResult.equals(sbResult));
        System.out.println("Speedup factor             : ~" + (naiveTime / Math.max(sbTime, 1)) + "x");
    }
}
Output
Comparing String concatenation vs StringBuilder over 50000 iterations.
Naive String concatenation : 3241 ms
StringBuilder : 4 ms
Results match : true
Speedup factor : ~810x
Pro Tip:
Pre-size your StringBuilder when you have a rough idea of the final length — new StringBuilder(estimatedLength). It avoids internal buffer re-allocations as the builder grows, squeezing out even more performance in tight loops.
Production Insight
The 810x speedup in the demo is real — but only for small strings. For large strings, the difference can be even more dramatic due to memory pressure.
StringBuffer's synchronized methods add ~10-20% overhead compared to StringBuilder in single-threaded use.
Rule: always prefer StringBuilder for local variable construction; reserve StringBuffer for genuinely shared builders (rare in practice).
Key Takeaway
String concatenation in loops is O(n^2) due to repeated copying and allocation.
StringBuilder is O(n) with a single allocation at the end.
Pre-size the buffer for maximum speed and minimal GC pressure.

Why Immutability Is a Security and Thread-Safety Feature

Here's a scenario that breaks insecure systems: imagine a class that validates a file path and then opens it. If Strings were mutable, a malicious thread could modify the path between the validation check and the file open call — a classic Time-of-Check to Time-of-Use (TOCTOU) attack. Because Strings are immutable, the path you validated is guaranteed to be the exact same bytes when you use it a millisecond later. No synchronisation needed.

This same guarantee is what makes Strings safe as HashMap keys. The hash code is computed once and cached inside the String object (the hash field). Because the content can never change, the cached hash never goes stale. If Strings were mutable, you could insert a key, mutate it, and the HashMap would never find it again because the bucket would be wrong.

Immutability also makes Strings inherently thread-safe. You can share one String reference across hundreds of threads with zero locking. This is enormous for performance in concurrent systems like web servers where the same configuration strings, URL patterns, and SQL templates are read constantly.

StringSecurityDemo.javaJAVA
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import java.util.HashMap;
import java.util.Map;

public class StringSecurityDemo {

    public static void main(String[] args) {

        // --- Demo 1: Safe HashMap key behaviour ---
        Map<String, String> configMap = new HashMap<>();
        String dbKey = "database.url";

        configMap.put(dbKey, "jdbc:postgresql://localhost:5432/mydb");

        // Even if we re-point dbKey, the original String in the map is safe
        dbKey = "something.else"; // re-points the variable, NOT the object in the map

        // The map still holds the original key — it's immutable inside the map
        System.out.println("DB URL from map : " + configMap.get("database.url"));

        // --- Demo 2: Cached hash code means one computation, reused forever ---
        String heavyKey = "user:profile:settings:theme";

        // First call computes and caches the hash inside the String object
        int firstHash  = heavyKey.hashCode();
        // Second call returns the cached value — O(1), no recomputation
        int secondHash = heavyKey.hashCode();

        System.out.println("\nHash code (first call)  : " + firstHash);
        System.out.println("Hash code (second call) : " + secondHash);
        System.out.println("Same hash               : " + (firstHash == secondHash));

        // --- Demo 3: Thread safety — shared String, no synchronisation needed ---
        String sharedConfig = "maxConnections=100";

        Runnable reader = () -> {
            // Totally safe — immutable object needs no locking
            System.out.println(Thread.currentThread().getName()
                    + " reads: " + sharedConfig);
        };

        Thread t1 = new Thread(reader, "Thread-1");
        Thread t2 = new Thread(reader, "Thread-2");
        t1.start();
        t2.start();
    }
}
Output
DB URL from map : jdbc:postgresql://localhost:5432/mydb
Hash code (first call) : -1732443147
Hash code (second call) : -1732443147
Same hash : true
Thread-1 reads: maxConnections=100
Thread-2 reads: maxConnections=100
Interview Gold:
When an interviewer asks 'Why is String immutable in Java?', give THREE reasons: security (safe to share without defensive copies), thread safety (no synchronisation needed), and performance (String Pool + cached hash code). Candidates who give all three — with examples — stand out.
Production Insight
TOCTOU vulnerabilities in file path validation are real — always validate on the immutable reference.
HashMap performance benefits from cached hash codes: calling hashCode() on a String repeatedly costs nothing after the first call.
Rule: if you need a mutable key, don't use String — use a custom class that breaks the hashCode contract (and deal with the consequences).
Key Takeaway
Immutability eliminates TOCTOU attacks by guaranteeing data doesn't change between check and use.
Strings as HashMap keys are safe and fast because their hash is cached.
No locks needed for reading Strings across threads — true shareability.

String Equality: The One Rule That Prevents Hours of Debugging

The most common production bug involving Strings is using == to compare values. This mistake is so prevalent that interviewers ask about it constantly, yet it still makes it into production code every day. The rule is simple: == checks if two references point to the same memory location; .equals() checks if the content of two strings is the same.

When does == work correctly? Only when both strings are guaranteed to be from the String Pool, i.e., both are literals like "hello". The moment one string comes from a method call, database, network, or new String(), == will return false even for identical text. That's why login checks, authorization logic, and configuration comparisons break silently.

There are two common workarounds that also fail: calling .intern() on every string before comparing, or using == with intern(). The first is expensive (interning has a global lock in some JVM implementations), the second is unreliable. The fix is always .equals(). For case-insensitive comparisons, use .equalsIgnoreCase().

Another subtle trap: null handling. Calling .equals() on a null reference throws NullPointerException. Use Objects.equals(str1, str2) which is null-safe, or invert the call: "knownValue".equals(unknownValue).

StringEqualityTrap.javaJAVA
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class StringEqualityTrap {

    public static void main(String[] args) {

        // --- Scenario 1: Both literals — == works (but don't rely on it) ---
        String s1 = "production";
        String s2 = "production";
        System.out.println("Literals with ==    : " + (s1 == s2)); // true

        // --- Scenario 2: One literal, one from a method ---
        BufferedReader reader = new BufferedReader(new FileReader("config.txt"));
        String s3 = reader.readLine(); // reads "production" from a file
        System.out.println("Literal vs IO with == : " + (s1 == s3)); // false!
        System.out.println("Literal vs IO with .equals() : " + s1.equals(s3)); // true

        // --- Scenario 3: Inverted call avoids NullPointerException ---
        String s4 = null;
        // s4.equals(s1); // NPE!
        String safe = "default".equals(s4) ? "same" : "different"; // works
        System.out.println("Inverted equals with null: " + safe); // "different"

        // --- Scenario 4: Objects.equals() is null-safe ---
        System.out.println("Objects.equals(null, null): " + Objects.equals(null, null)); // true
        System.out.println("Objects.equals(null, s1): " + Objects.equals(null, s1)); // false
    }
}
Output
Literals with == : true
Literal vs IO with == : false
Literal vs IO with .equals() : true
Inverted equals with null: different
Objects.equals(null, null): true
Objects.equals(null, s1): false
Production-Fatal:
Never use == to compare String values that originate from external sources (DB, API, files). Always use .equals(). This single rule prevents more production outages than any other String-related advice.
Production Insight
A common production pattern: reading configuration values from a properties file and comparing with == in authorization checks — fails silently when the expected value is a literal but the configured value is from a file.
Using Objects.equals() or inverted equals is a defensive habit that prevents NPE at 3 AM.
Rule: when in doubt about null, use String.valueOf(Object) or Objects.toString() before comparison.
Key Takeaway
== compares references, not content — use .equals() for all value comparisons.
Null-safe comparison always: "constant".equals(variable) or Objects.equals(a, b).
Don't use intern() as a workaround for == — it's expensive and still not a substitute for semantic equality.
● Production incidentPOST-MORTEMseverity: high

The TOCTOU Exploit That Immutability Prevented

Symptom
Intermittent security alerts: users could access files outside their allowed directory. The bug only reproduced under heavy load, making it a nightmare to debug.
Assumption
The validation method created a new String object from user input, passed it to the file access method, and assumed no one could change it in between.
Root cause
The original design used a mutable StringBuilder to parse the path before validation, then converted it to a String. The developer assumed the String was safe, but the validation was actually performed on a StringBuilder that could be modified by another thread before the final .toString() call.
Fix
Moved the validation to the final String object (immutable) and ensured that any mutable operations on the path were completed and converted to a String before the security check. The fix was a one-line change: use a local String variable to hold the validated path, not a StringBuilder reference that escapes.
Key lesson
  • Do not validate a mutable object and then use it as if it were immutable — convert to String first.
  • Immutability is a guarantee only if the reference you hold is to an immutable object.
  • Always finalize string construction (e.g., StringBuilder.toString()) before performing security-sensitive checks.
  • Immutable objects remove an entire class of TOCTOU vulnerabilities — use them intentionally.
Production debug guideSymptom → Action guide for the most common string problems in production5 entries
Symptom · 01
Login fails intermittently for users whose passwords are loaded from a database
Fix
Check if the password comparison uses == instead of .equals(). Database-driven strings are not pooled — == compares references and will return false even for identical content.
Symptom · 02
Application slows down noticeably when processing large CSV files or logs with string concatenation in a loop
Fix
Profile memory allocations: look for high number of String objects being created. Replace any visible string concatenation (+=) inside loops with StringBuilder and call .toString() once after the loop.
Symptom · 03
OutOfMemoryError: Java heap space in a batch job that builds strings
Fix
Check if the job uses String or StringBuffer instead of StringBuilder. If StringBuffer is used, evaluate if synchronization is truly needed. Pre-size the StringBuilder with an estimated capacity to avoid internal array resizing.
Symptom · 04
HashMap get() returns null for a key that was inserted with seemingly the same string
Fix
Verify that the hashCode() implementation is not compromised by mutable objects used as keys. For Strings, this is safe. But if the key was constructed with new String(), the hash code is still correct — check that the actual string content matches (spaces, encoding). Use .equals() for key lookup, not ==.
Symptom · 05
Security audit reveals potential path traversal vulnerability
Fix
Ensure that file path strings used in access control are immutable when validated. Check that no mutable objects (StringBuilder, StringBuffer) are being modified after validation. Convert all path building to final String objects before the security check.
★ Quick Debug Cheat Sheet: String Issues in ProductionUse these exact commands and steps when you suspect a string-related problem in production.
String equality bug (using ==)
Immediate action
Check the comparison operator in the source — grep for 'str1 == str2' or similar patterns in the codebase.
Commands
grep -rn '== .*"' src/main/java/
System.out.println(str1.equals(str2)); // add for verification
Fix now
Replace == with .equals(). If you need case-insensitive, use .equalsIgnoreCase().
Performance issue with string concatenation in a loop+
Immediate action
Identify the loop by profiling memory allocations — look for StringBuilder (or its absence) in stack traces.
Commands
jcmd <pid> GC.heap_dump /tmp/heap.hprof
Use jhat or Eclipse MAT to find many repeated String objects
Fix now
Create a StringBuilder before the loop, use append() inside, call toString() once after the loop.
StringPool overflow or PermGen errors (Java 6 and earlier)+
Immediate action
Check the number of unique interned strings in the pool. This is rare on Java 7+.
Commands
jcmd <pid> VM.native_memory summary
For Java 6: jmap -permstat <pid>
Fix now
Upgrade to Java 7+ where StringPool lives on heap and is GC-able, or reduce calls to intern() on large datasets.
NullPointerException when calling methods on a String+
Immediate action
Find the reference that is null — it may have been assigned a null from a database query or JSON parsing.
Commands
Add a null check: if (str == null) throw new IllegalArgumentException("String must not be null");
Use Optional.ofNullable(str).orElse("") for safe default
Fix now
Determine why the value is null and fix the upstream source (e.g., database column default, API contract).
String vs StringBuilder vs StringBuffer
Feature / AspectStringStringBuilderStringBuffer
MutabilityImmutable — every change is a new objectMutable — modifies internal buffer in-placeMutable — modifies internal buffer in-place
Thread SafetyInherently thread-safe (immutable)Not thread-safe — single-threaded use onlyThread-safe — all methods are synchronized
Performance (single thread)Slow for repeated modification (new objects)Fastest — no synchronisation overheadSlower than StringBuilder due to sync locks
String Pool cachingYes — literals are pooled and reusedNo — not eligible for poolingNo — not eligible for pooling
Hash code cachingYes — computed once, stored in hash fieldNo — content changes, so hash can't be cachedNo — content changes, so hash can't be cached
Typical use caseConfiguration, keys, constants, API paramsBuilding strings in loops or methodsLegacy multi-threaded string building
When to prefer itAlmost always for read-only textAny loop-based or programmatic assemblyRarely — prefer restructuring over StringBuffer

Key takeaways

1
Immutability means the String object never changes
but the variable can be re-pointed to a new object at any time. These are two completely different things.
2
The String Pool reuses literal objects safely because Strings can't change
sharing a reference is only safe when no one can mutate what it points to.
3
String concatenation inside a loop creates one new object per iteration
always replace loop concatenation with StringBuilder and call .toString() once at the end.
4
Three reasons String is immutable that interviewers want to hear
thread safety (share freely, no locks), security (validated value can't be swapped), and performance (String Pool + cached hash code).
5
Never use == to compare String values in production
always use .equals(). For null-safe comparison, use Objects.equals() or invert the call.

Common mistakes to avoid

5 patterns
×

Using `==` to compare String values

Symptom
Two Strings with identical text return false, causing silent logic bugs (e.g., a login check that always fails for passwords loaded from a database)
Fix
Always use .equals() for value comparison. Save == for intentional reference/identity checks only.
×

Concatenating Strings inside a loop with `+=`

Symptom
Noticeable slowdown or OutOfMemoryError on large datasets, because each iteration allocates a new String object and the previous one becomes garbage
Fix
Replace the loop body with StringBuilder.append() and call .toString() exactly once after the loop completes.
×

Calling `new String("literal")` thinking it creates a distinct safer copy

Symptom
Unnecessary heap allocation, and == comparisons with pooled literals silently return false, causing confusion
Fix
Use string literals directly (String s = "value") in virtually all cases; only use new String(charArray) when you genuinely need to construct a String from a char array or byte array.
×

Using `StringBuffer` in single-threaded code because 'it's safer'

Symptom
Unnecessary performance overhead from synchronized methods, typically 10-20% slower than StringBuilder
Fix
Use StringBuilder for all single-threaded string construction. Reserve StringBuffer only for cases where the builder object is shared across threads (rare).
×

Not handling null safely when comparing strings

Symptom
NullPointerException at runtime when the string is null and you call .equals() on it
Fix
Use Objects.equals(str1, str2) or invert the call: "known".equals(unknown). Avoid calling methods on potentially null references.
INTERVIEW PREP · PRACTICE MODE

Interview Questions on This Topic

Q01SENIOR
Why is the String class declared `final` in Java, and what would break i...
Q02SENIOR
Explain the Java String Pool. What is the difference between `String s =...
Q03SENIOR
If Strings are immutable, how does Java's HashMap use them as keys safel...
Q04JUNIOR
Why does `StringBuilder` exist when we already have `StringBuffer`? What...
Q05SENIOR
How would you optimize a method that builds a large string (e.g., an HTM...
Q01 of 05SENIOR

Why is the String class declared `final` in Java, and what would break if it weren't?

ANSWER
String is declared final to prevent subclassing that could break immutability. If you could subclass String, a malicious subclass could override methods like charAt() or hashCode() to return different values, violating the contract that strings are immutable. This would break String Pool safety, HashMap key behavior, and security mechanisms like path validation where the integrity of the string is assumed. In short: immutability is only as strong as the class hierarchy permits — final is the lock on the door.
FAQ · 7 QUESTIONS

Frequently Asked Questions

01
Why is String immutable in Java?
02
Does immutability mean I can't change a String variable?
03
When should I use StringBuilder instead of String concatenation?
04
What's the difference between StringBuffer and StringBuilder?
05
How does the String Pool work?
06
What does the `intern()` method do?
07
Why is it safe to use String as a HashMap key?
🔥

That's Strings. Mark it forged?

5 min read · try the examples if you haven't

Previous
String Comparison in Java
7 / 15 · Strings
Next
String Pool in Java