1.
The Core Philosophy: Immutability
In Java, a String is an object that represents a sequence of characters. The most
defining characteristic of a String is that it is immutable. Once a String object is
created, its value cannot be changed.
Thread Safety: Since Strings cannot change, they are inherently thread-safe.
Security: Sensitive data (like usernames or network connections) won't be
altered unexpectedly.
Caching: Immutability is what allows the "String Pool" to exist.
2. The String Constant Pool
When you create a string using a literal (e.g., String s = "Hello"), Java checks a special
memory area called the String Constant Pool (located within the Heap).
If the string "Hello" already exists in the pool, Java simply returns a reference to
that existing object.
If you use the new keyword (e.g., String s = new String("Hello")), Java is forced to
create a new object in the heap, bypassing the pool's e iciency.
3. String vs. StringBuilder vs. StringBu er
Because Strings are immutable, concatenating them in a loop (using +) is a
performance nightmare. Every + operation creates a brand new String object.
Feature String StringBuilder StringBu er
Mutability Immutable Mutable Mutable
Thread Safe Yes No Yes
Performance Slow (for mods) Fast Medium
Pro Tip: Always use StringBuilder for heavy string manipulation within a single thread
to avoid flooding your heap with garbage objects.
4. Common Operations & Pitfalls
Equality Testing
Never use == to compare the content of two strings.
== checks if the references (memory addresses) are the same.
.equals() checks if the sequences of characters are the same.
Internal Representation
As of Java 9, Strings underwent a major optimization called Compact Strings.
Before: Stored as a char[] (2 bytes per character).
After: Stored as a byte[] with an encoding flag. If the string only contains Latin-1
characters, it takes up half the space it used to.
5. Performance Best Practices
1. Use Literals: Prefer String s = "abc" over new String("abc").
2. Pre-size StringBuilders: If you know your final string will be roughly 10,000
characters, initialize it with new StringBuilder(10000) to avoid multiple array
copies.
3. Interning: You can manually move a string created with new into the pool using
the .intern() method, though this is rarely necessary in modern Java.