String intern() method in Java
In Java, the String
class is one of the most fundamental classes, offering a wide array of methods to manipulate strings. One such method is intern()
, which plays a unique role in managing string literals within the Java Virtual Machine (JVM).
What is the intern() method?
The intern()
method is used to optimize memory by storing unique strings in the “string pool”. The string pool is a special area in the heap memory where Java keeps unique string literals. When intern()
is invoked on a string, the JVM checks if an equivalent string is already present in the pool. If it finds a match, it returns a reference to that string. Otherwise, it adds the string to the pool and returns a reference to it.
How does intern() work?
Let’s consider an example to illustrate its usage:
String str1 = "Hello";
String str2 = new String("Hello").intern();
In this example:
str1
is a string literal, so it’s automatically added to the string pool.str2
is explicitly interned using theintern()
method, ensuring it references the same string object asstr1
.
Benefits of intern() method
- Memory Optimization: By using
intern()
, you can reduce memory consumption when dealing with multiple instances of the same string. - Comparing Interned Strings: It becomes efficient to compare strings using
==
when both strings are interned, as it checks for reference equality.
Similar Post: Java 11- New Methods of String Class
Best Practices and Considerations
While the intern()
method can be useful for certain scenarios, it’s essential to use it judiciously:
- Memory Overhead: The string pool can grow large if too many strings are interned, potentially impacting performance.
- Automatic Interning: String literals are automatically interned, so explicit use of
intern()
is typically necessary when dealing with dynamically created strings.
Let’s explore scenarios where intern()
proves beneficial:
Scenario 1: Using intern()
for String Comparison
String str1 = "apple";
String str2 = new String("apple").intern();
System.out.println(str1 == str2); // Outputs: true
Here, both str1
and str2
reference the same interned string, resulting in true
for the comparison.
Scenario 2: String Pool Management
String bigString = ""; // Initialize an empty string
for (int i = 0; i < 100000; i++) {
bigString += i;
}
bigString = bigString.intern();
In this scenario, bigString
is constructed by appending numbers repeatedly. Interning bigString
helps prevent the accumulation of too many unique string instances in memory.
Summary
The intern()
method in Java’s String
class is a powerful tool for managing string literals and optimizing memory usage. However, it should be used judiciously, considering its impact on memory and performance. By intelligently using intern()
, developers can efficiently manage string literals and enhance their application’s performance.