The String.intern() method returns a canonical representation from the JVM String Constant Pool (SCP) for the target string.
Memory Deduplication & Reference Equality: If the pool already contains a string equal to this object by equals(), the pooled instance is returned; otherwise, this string is added to the pool. This allows comparing strings with fast reference equality (==). To compare string content without pooling, see compareTo(). For hash generation, explore hashCode(), or check for empty text with isEmpty().
The intern() method takes zero parameters and is declared in java.lang.String:
// Formal signature of String.intern() in java.lang.String
public String intern()
| Signature Element | Type | Description & Operational Contract |
|---|---|---|
| Parameters | None | Invoked directly on any non-null string instance. |
| Return Value | String |
The canonical instance from the JVM String Constant Pool. |
| Identity Guarantee | s.intern() == t.intern() |
Guaranteed true if, and only if, s.equals(t) is true. |
Contrasting string literals, newly allocated heap strings, and interned canonical references:
String s1 = "plus2net";
String s2 = "plus2net";
String s3 = new String("plus2net");
String s4 = s3.intern();
System.out.println("s1 == s2: " + (s1 == s2)); // true (both reference String Pool literal)
System.out.println("s2 == s3: " + (s2 == s3)); // false (s3 is a separate object on heap)
System.out.println("s4 == s2: " + (s4 == s2)); // true (s4 references the pooled instance)Terminal Output:
s1 == s2: true
s2 == s3: false
s4 == s2: true
Strings built at runtime via concat() or the + operator are created on the normal heap outside the pool. Calling intern() explicitly links them to the pool:
String part1 = "plus2";
String part2 = "net";
// Concatenated at runtime: allocated on standard heap, NOT automatically interned
String dynamicStr = part1 + part2;
String literalStr = "plus2net";
System.out.println("dynamic == literal: " + (dynamicStr == literalStr)); // false
// Calling intern() retrieves pooled reference matching the dynamic characters
String internedStr = dynamicStr.intern();
System.out.println("interned == literal: " + (internedStr == literalStr)); // trueTerminal Output:
dynamic == literal: false
interned == literal: true
When strings are guaranteed to be interned, developers can compare them using the == operator in O(1) time instead of scanning character by character:
String a = new String("Java");
String b = new String("Java");
// Without intern(): equals() performs character-by-character scan
System.out.println("a == b: " + (a == b)); // false
System.out.println("a.equals(b): " + a.equals(b)); // true
// With intern(): references point to identical memory location
System.out.println("a.intern() == b.intern(): " + (a.intern() == b.intern())); // trueTerminal Output:
a == b: false
a.equals(b): true
a.intern() == b.intern(): true
The internal architecture of Java's String Constant Pool has evolved significantly:
| Java Version | Memory Storage Area | Garbage Collection Behavior |
|---|---|---|
| Java 6 & Earlier | PermGen (Permanent Generation) | Rarely garbage-collected; prone to OutOfMemoryError: PermGen. |
| Java 7 & Java 8+ | Main Java Heap | Fully eligible for standard garbage collection when unreferenced. |
| Java 8u20+ (G1GC) | Main Heap + String Deduplication | Optional -XX:+UseStringDeduplication shares char arrays automatically. |
When processing millions of records with repeating values (such as state or country codes), interning reduces heap memory footprints by orders of magnitude:
import java.util.ArrayList;
import java.util.List;
public class CountryDataParser {
public static void main(String[] args) {
// Simulating parsing thousands of rows with repeating country codes
String[] incomingRows = {"US", "IN", "US", "DE", "IN", "US", "IN"};
List<String> records = new ArrayList<>();
for (String code : incomingRows) {
// Interning ensures all repeated records share the exact same reference
records.add(code.intern());
}
// Verify that duplicate rows share the exact same memory instance
System.out.println("First 'US' == Third 'US': " + (records.get(0) == records.get(2))); // true
System.out.println("Second 'IN' == Fifth 'IN': " + (records.get(1) == records.get(4))); // true
}
}Terminal Output:
First 'US' == Third 'US': true
Second 'IN' == Fifth 'IN': true
Ensuring repeated XML node attributes or JSON field keys share canonical instances across parsers:
public class TagInternOptimizer {
public static String normalizeTag(String parsedTag) {
if (parsedTag == null) return null;
// Intern common XML/JSON key names to avoid millions of duplicated string instances
return parsedTag.toLowerCase().intern();
}
public static void main(String[] args) {
String tag1 = normalizeTag("ID");
String tag2 = normalizeTag("id");
System.out.println("Same canonical tag instance? " + (tag1 == tag2)); // true
}
}Terminal Output:
Same canonical tag instance? true
Using System.identityHashCode() to confirm that interned strings share the exact same physical heap object:
// Visualizing memory address differences via System.identityHashCode()
String lit = "Oracle";
String heapObj = new String("Oracle");
String pooledRef = heapObj.intern();
System.out.println("Literal identity hash: " + System.identityHashCode(lit));
System.out.println("Heap obj identity hash: " + System.identityHashCode(heapObj));
System.out.println("Pooled ref identity: " + System.identityHashCode(pooledRef));Terminal Output:
Literal identity hash: 1828972342
Heap obj identity hash: 1452126962
Pooled ref identity: 1828972342
Interning billions of unique, temporary strings (e.g. UUIDs or transaction IDs) pollutes the JVM string table hash map, increasing CPU overhead. Only intern strings with high repetition rates.
Calling str.intern() without assigning the returned reference leaves str pointing to the original heap object! Always write str = str.intern().
You can compile and run this complete verification class locally in any Java IDE or environment:
public class StringInternFullDemo {
public static void main(String[] args) {
String base = "plus2net";
String custom = new String("plus2net");
// 1. Verify heap object differs from pool literal
if (base != custom) {
System.out.println("Check 1 Passed: Distinct heap allocation confirmed.");
}
// 2. Verify intern() returns pooled reference
if (custom.intern() == base) {
System.out.println("Check 2 Passed: intern() returned pooled instance reference.");
}
// 3. Verify value equality contract
if (custom.equals(base) && (custom.intern() == base.intern())) {
System.out.println("Check 3 Passed: Value equality matches canonical reference equality.");
}
System.out.println("All String.intern() verification checks passed successfully!");
}
}Terminal Output:
Check 1 Passed: Distinct heap allocation confirmed.
Check 2 Passed: intern() returned pooled instance reference.
Check 3 Passed: Value equality matches canonical reference equality.
All String.intern() verification checks passed successfully!
Yes. All string literals and constant expressions (such as "hello") are automatically interned by the Java compiler during class loading.
In Java 7 and newer, interned strings reside in the main heap and are fully eligible for garbage collection when no longer referenced.
Use it when parsing massive datasets (millions of rows) containing a small set of heavily repeated string values, such as ISO codes, status flags, or categories.
Calling null.intern() throws an immediate NullPointerException. Guard your variables with isEmpty() or null checks.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.