Java
String intern
String literals
Java optimization
memory management

When should we use intern method of String on String literals

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Overview

The intern() method of the String class in Java can be a valuable tool when dealing with large numbers of strings, particularly in scenarios where memory optimization is critical. Understanding when and how to use this method effectively can directly impact the performance of your Java applications.

What is the intern() Method?

The intern() method in Java is a native method provided by the String class. The primary purpose of this method is to manage the memory consumed by strings via the String Intern Pool. Essentially, this method returns a canonical representation for the string object.

When you call intern() on a string, it checks whether the string already exists in the String Intern Pool:

  • If the string is already present, a reference to the pooled instance is returned.
  • If it is not present, the method adds the string to the pool and returns the reference to the newly added string.

Understanding String Intern Pool

String Intern Pool is a special memory space within the Java heap designated for storing string literals. By maintaining a pool of strings, Java can reduce memory consumption and speed up string manipulations by reusing existing string instances.

When to Use the intern() Method

1. Reducing Memory Usage

When working with applications that handle a significant number of repeated string values, interning can drastically reduce memory usage by ensuring that only one instance of each unique string is retained in the pool. Instead of creating a new object for each occurrence, references to the pooled object are used.

Example:

java
1String s1 = new String("example").intern();
2String s2 = new String("example").intern();
3
4System.out.println(s1 == s2); // Output: true, because both reference the same interned object.

2. Improving Performance in Large-Scale Applications

In large-scale applications where strings are frequently compared, using intern() can improve performance. Since interning ensures that identical strings share the same memory reference, string comparison can be reduced to reference comparison, which is faster than character-by-character comparison.

Example:

java
1String s1 = "performance";
2String s2 = new String("performance").intern();
3
4if (s1 == s2) {
5    System.out.println("Interned strings matched via reference!");
6}

3. Serialization and Deserialization

When objects are serialized and deserialized in Java, interning string values can help maintain a consistent set of string instances across distributed systems or when loading data into memory, reducing memory consumption and potentially speeding up operations.

Considerations and Best Practices

  • String Literals are Auto-Interned: Remember that string literals are automatically interned by the JVM. Explicitly calling intern() on a string literal is unnecessary as they are inherently part of the pool.
  • Impact on Performance: While intern() can reduce memory footprint, keep in mind that adding to the pool during runtime has a performance cost. Excessive use of intern() might negate some benefits due to additional processing time required to manage the pool.
  • Heap Size Considerations: Since the String Intern Pool resides in the heap memory, using intern() increases usage of heap space and can lead to out-of-memory errors if not managed carefully with large datasets.

Technical Example

To illustrate the basic usage and benefits of the intern() method in an application, consider the following code snippet.

java
1import java.util.HashMap;
2
3public class StringInterningExample {
4    public static void main(String[] args) {
5        HashMap<String, Integer> wordCount = new HashMap<>();
6        String[] words = {"hello", "world", "hello", "intern", "world"};
7
8        for (String word : words) {
9            String internedWord = word.intern();
10            wordCount.put(internedWord, wordCount.getOrDefault(internedWord, 0) + 1);
11        }
12
13        System.out.println(wordCount);
14    }
15}

In this example, the intern() method helps reduce memory usage by ensuring that repeated words refer to the same memory location.

Summary Table

AspectDetails
PurposeShare common string instances to save memory.
Works OnBoth string literals and new String objects.
Automatic for LiteralsYes, literals are auto-interned by JVM.
Performance ImpactMay improve string comparisons, but has interning overhead.
Memory ConsiderationsReduces usage by sharing, but adds load on JVM's heap.
Best ForLarge-scale systems, serialization, and high-frequency strings.

Conclusion

Understanding the efficient use of the intern() method can play a crucial role in optimizing Java applications. By leveraging the intern pool strategically, one can achieve reductions in memory consumption and, at times, performance improvements. However, care should be taken to balance its usage to avoid negative impacts due to excessive heap demands.


Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.