Strings in memory and interning
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A String in modern Java is two objects: a small String object and a byte[] holding its characters. Which String object you get, a shared one from the String pool or a new one, decides what == says, and the way the characters are stored decides how much memory your text really costs.
Literals go to the String pool; new String makes a new object
The String pool is a table of shared String objects, one per distinct text. It holds every string literal and every interned string, and it lives on the heap since Java 7.
The String pool (HotSpot calls it the StringTable) is a table of shared String objects, one per distinct text.
Example 1 · The String pool, new String and compile-time joining
public class StringPoolDemo { public static void main(String[] args) { String a = "Mumbai"; // literal: taken from the String pool String b = "Mumbai"; String c = new String("Mumbai"); // new always makes a new String object
System.out.println("a == b : " + (a == b)); System.out.println("a == c : " + (a == c)); System.out.println("a.equals(c) : " + a.equals(c));
String joined = "Mum" + "bai"; System.out.println("a == \"Mum\" + \"bai\" : " + (a == joined));
String part = "Mum"; String runtime = part + "bai"; // a variable is involved: built at run time System.out.println("a == part + \"bai\" : " + (a == runtime));
final String fixed = "Mum"; System.out.println("a == fixed + \"bai\" : " + (a == fixed + "bai")); }}a == b : true a == c : false a.equals(c) : true a == "Mum" + "bai" : true a == part + "bai" : false a == fixed + "bai" : true
What this code does
aandbare the same pooled object.new Stringmakes a separate object, soa == cisfalsebutequalsistrue."Mum" + "bai"andfixed + "bai"are constant expressions that javac joins into the literal"Mumbai", so they are pooled.part + "bai"uses a normal variable and is built at run time.
Every string literal in your code, such as "Mumbai", is looked up in the pool, so the same literal anywhere in the program gives the same object. new String("Mumbai") always creates a new String object, so == with the literal is false while equals is true. javac also joins literals at compile time: "Mum" + "bai" becomes the literal "Mumbai", and so does a final constant plus a literal. Text built at run time from a variable is a new object.
Since Java 7 the pool lives in the normal heap, not in PermGen, so pooled strings that nothing uses any more can be garbage collected like other objects.
Find the bug
Find the string comparison bug
Each check can give the wrong answer. Tap the wrong line, then check the fix.
Check the city that the user typed.
Round 1 of 3intern() and when it helps
s.intern() returns the pooled String with the same text as s. If the pool has none yet, it adds one. After interning, equal texts are the same object, so a.intern() == b.intern() is true whenever a.equals(b).
Example 2 · intern() turns 10,000 copies into 5 objects
import java.util.ArrayList;import java.util.IdentityHashMap;import java.util.List;
public class InternDemo { static int distinctObjects(List<String> list) { IdentityHashMap<String, Boolean> seen = new IdentityHashMap<>(); // counts objects, not texts for (String s : list) { seen.put(s, Boolean.TRUE); } return seen.size(); }
public static void main(String[] args) { String[] cities = {"Pune", "Delhi", "Patna", "Surat", "Kochi"}; List<String> plain = new ArrayList<>(); List<String> interned = new ArrayList<>();
for (int i = 0; i < 10_000; i++) { String line = (1000 + i) + "," + cities[i % cities.length]; // like one CSV row String city = line.split(",")[1]; plain.add(city); interned.add(city.intern()); // the pooled copy }
System.out.println("Rows: " + plain.size()); System.out.println("City objects without intern: " + distinctObjects(plain)); System.out.println("City objects with intern: " + distinctObjects(interned)); System.out.println("Pooled Pune == literal? " + (interned.get(0) == "Pune")); }}Rows: 10000 City objects without intern: 10000 City objects with intern: 5 Pooled Pune == literal? true
What this code does
splitcreates a newStringfor the city on every row, so 10,000 rows give 10,000 city objects.IdentityHashMapcounts objects, not texts.city.intern()returns the pooled copy, so all rows share 5 objects. The pooled"Pune"is the same object as the literal"Pune".
It helps when a program keeps a very large number of copies of a few repeated values for a long time: city or branch names read from millions of CSV rows, status codes, country codes. Each repeated value then costs one object instead of thousands. It does not help for mostly unique strings (names, emails, OTPs): each call costs a table lookup and the pool only grows. And it is never a reason to compare strings with ==; keep using equals.
HashMap<String, String> as a pool, because they can clear it when the data is no longer needed.Compact strings: LATIN1 or UTF16 (Java 9 and later)
Compact strings (Java 9 and later) store a string's characters in a byte[] with a coder field that says how.
Example 3 · Measured: LATIN1 versus UTF16 names
import java.util.ArrayList;import java.util.List;
public class CompactStringsDemo { static long usedAfterGc() { System.gc(); // a request, not a promise Runtime rt = Runtime.getRuntime(); return rt.totalMemory() - rt.freeMemory(); }
// 20 characters per name; 'base' picks the alphabet static String name(int i, char base) { StringBuilder sb = new StringBuilder(); for (int k = 0; k < 20; k++) { sb.append((char) (base + (i + k) % 20)); } return sb.toString(); }
static long measure(char base, int n) { long before = usedAfterGc(); List<String> names = new ArrayList<>(n); for (int i = 0; i < n; i++) { names.add(name(i, base)); } long grew = usedAfterGc() - before; System.out.println(" check: " + names.size() + " names of length " + names.get(0).length()); return grew / n; }
public static void main(String[] args) { int n = 200_000; System.out.println("English letters (LATIN1, 1 byte each):"); long latin = measure('a', n); System.out.println("Hindi letters (UTF16, 2 bytes each):"); long hindi = measure((char) 0x0915, n); // Devanagari letters from KA onwards System.out.println("About " + latin + " bytes per English name"); System.out.println("About " + hindi + " bytes per Hindi name"); }}English letters (LATIN1, 1 byte each): check: 200000 names of length 20 Hindi letters (UTF16, 2 bytes each): check: 200000 names of length 20 About 66 bytes per English name About 85 bytes per Hindi name
What this code does
- Estimate for 20 English letters: 24 (String) + 40 (16 + 20 bytes, rounded) + 4 (list slot) = 68 bytes. For 20 Hindi letters: 24 + 56 (16 + 40) + 4 = 84 bytes.
- The measured numbers are close. The Hindi names are built from character codes starting at
0x0915(the letter KA), so the program prints no Hindi text. Your numbers will differ slightly.
If every character fits in one byte (Latin-1: English letters, digits, most Western European letters such as é), the coder is LATIN1 and each character takes 1 byte. Otherwise the coder is UTF16 and every character takes 2 bytes.
Before Java 9 every String used a char[], 2 bytes per character. Most strings in most programs are plain English or digits, so compact strings roughly halve the character data. One character outside Latin-1, such as ₹ or a Hindi letter, makes the whole string UTF16. Estimate: the String object is 24 bytes, plus the array: roundUpTo8(16 + length × 1 or 2). The feature is on by default; -XX:-CompactStrings turns it off.
substring copies characters (since Java 7u6)
substring returns a new String with its own copy of the selected characters (since Java 7 update 6). Before that, a substring shared the big string's character array and only stored an offset and a length.
Example 4 · A small substring does not keep the big text alive
import java.util.ArrayList;import java.util.List;
public class SubstringDemo { static long usedAfterGc() { System.gc(); // a request, not a promise Runtime rt = Runtime.getRuntime(); return rt.totalMemory() - rt.freeMemory(); }
// Reads 200 big "files" of about 130 KB each and keeps either the whole text or one PNR. static long keep(boolean wholeText, List<String> kept) { long before = usedAfterGc(); for (int i = 0; i < 200; i++) { String bigFile = ("PNR" + (4521367890L + i)).repeat(10_000); kept.add(wholeText ? bigFile : bigFile.substring(0, 13)); } return (usedAfterGc() - before) / (1024 * 1024); }
public static void main(String[] args) { String pnr = "PNR4521367890"; System.out.println("substring(0) is the same object? " + (pnr.substring(0) == pnr)); System.out.println("substring(3) is a new object? " + (pnr.substring(3) != pnr));
List<String> pnrs = new ArrayList<>(); long small = keep(false, pnrs); System.out.println("Keeping 200 substrings: heap grew about " + small + " MB, first = " + pnrs.get(0));
List<String> files = new ArrayList<>(); long big = keep(true, files); System.out.println("Keeping 200 whole texts: heap grew about " + big + " MB, " + files.size() + " kept"); }}substring(0) is the same object? true substring(3) is a new object? true Keeping 200 substrings: heap grew about 0 MB, first = PNR4521367890 Keeping 200 whole texts: heap grew about 24 MB, 200 kept
What this code does
- Each "file" is about 130 KB of text. Keeping only
substring(0, 13)copies 13 characters, so the big strings become garbage and the heap barely grows. - Keeping the whole texts costs about 200 × 130 KB, close to 25 MB. On Java 6 the first case would also have kept about 25 MB alive. Your numbers will differ slightly.
The old way made substring fast but caused a classic leak: keeping a 10-character substring of a 1 MB line kept the whole 1 MB alive. Today the big string can be collected as soon as nothing refers to it. The cost is that substring now takes time and memory in proportion to its length. One special case: s.substring(0) and s.substring(0, s.length()) return s itself, because nothing changes.
G1 string deduplication with -XX:+UseStringDeduplication
String deduplication is a background GC feature that finds String objects with equal text and makes them share one byte[]. Turn it on with -XX:+UseStringDeduplication. It came with G1 in Java 8u20; since Java 18 the Serial, Parallel and Z collectors support it too.
Example 5 · Duplicate strings that deduplication can share
import java.util.ArrayList;import java.util.List;
public class DedupDemo { static byte[] last; // keeps the JIT from removing the garbage loop
public static void main(String[] args) { String[] cities = {"Bengaluru", "Hyderabad", "Chennai", "Pune", "Kolkata"}; List<String> addresses = new ArrayList<>(); for (int i = 0; i < 100_000; i++) { // like text read from a file: a new String with its own byte[] each time addresses.add(new StringBuilder(cities[i % cities.length]).toString()); }
long junk = 0; for (int i = 0; i < 300_000; i++) { last = new byte[1024]; // short-lived garbage, so young GCs happen junk += last.length; }
System.out.println("Same object? " + (addresses.get(0) == addresses.get(5))); System.out.println("Equal text? " + addresses.get(0).equals(addresses.get(5))); System.out.println("Strings kept: " + addresses.size() + ", garbage made: " + junk / 1024 / 1024 + " MB"); }}Same object? false Equal text? true Strings kept: 100000, garbage made: 292 MB
What this code does
new StringBuilder(city).toString()gives every address its ownStringand its ownbyte[], like text read from a file or a database. 100,000 strings hold only 5 different texts.- The loop of
new byte[1024]makes short-lived garbage, so young collections happen while the strings are alive. Writing to the static fieldlaststops the JIT from removing the loop.
Example 6 · Turning on string deduplication and reading its log
java -XX:+UseStringDeduplication -Xlog:gc,stringdedup DedupDemo[0.023s][info][gc] Using G1 [0.287s][info][gc ] GC(0) Pause Young (Normal) (G1 Evacuation Pause) 23M->6M(118M) 20.745ms [0.302s][info][gc ] GC(1) Pause Young (Normal) (G1 Evacuation Pause) 31M->6M(118M) 6.428ms [0.308s][info][stringdedup] Concurrent String Deduplication 116/4008.0B (new), 64496/1713.2K (deduped), avg 2242.9%, 20.420ms of 20.423ms [0.314s][info][stringdedup] Concurrent String Deduplication 189/9600.0B (new), 35532/944.0K (deduped), avg 3098.4%, 6.404ms of 6.406ms [0.380s][info][gc ] GC(2) Pause Young (Normal) (G1 Evacuation Pause) 75M->6M(118M) 1.892ms ... Same object? false Equal text? true Strings kept: 100000, garbage made: 292 MB
What this code does
- A real run on OpenJDK 21 with G1, trimmed: lines where nothing was deduplicated are left out.
-Xlog:gc,stringdedupprints GC pauses and deduplication results. - 64,496 + 35,532 strings were deduplicated, about 2.6 MB of arrays now shared. The program's own output is unchanged: the
Stringobjects are still different, so==staysfalse.
It is off by default. It only shares the arrays: the String objects stay separate, so == is still false and your code behaves the same. It looks only at strings that have survived a few collections (3 by default, StringDeduplicationAgeThreshold), so short-lived strings cost nothing.
Use it when a heap dump shows many duplicate strings that you cannot easily change in code. It saves the array part only, about 24 to 40 bytes per short duplicate, and adds a little background GC work.
Next step
Check your understanding
12 quick questions