Java String intern()
method is used to manage memory by reducing the number of String
objects created. It ensures that all same strings share the same memory.
For example, creating a string “hello” 10 times using intern()
method would ensure that there will be only one instance of “Hello” in the memory and all the 10 references point to the same instance.
How intern() Works
When you use intern()
method on a String, it does following in order:
- It checks if an identical string is already present in the intern pool.
- If It finds an identical string in the pool, instead of creating new string, it returns the reference from the pool.
- If it doesn’t find an identical string, it adds the string to the pool and returns the reference to this new entry.
Basic Syntax
String internedString = str.intern();
Java String intern() method Examples
1. Creating intern String using intern() method and literal
In this example:
str1
is a new string object.str2
is a string literal, these are automatically interned, which means creating string literal is same as callingintern()
method on an identical string.str3
is created usingintern()
onstr1
, which makesstr3
reference the same interned string asstr2
.
public class Example{
public static void main(String args[]){
String str1 = new String("Hello");
String str2 = "Hello";
String str3 = str1.intern();
System.out.println(str1 == str2); // Output: false
System.out.println(str2 == str3); // Output: true
}
}
2. Memory management using intern() method
Here, strings str1
and str2
are two different objects with the same content. Calling intern()
method on any of these strings would point to the same interned string.
public class Example{ public static void main(String args[]){ String str1 = new String("BeginnersBook"); String str2 = new String("BeginnersBook"); // Output: false as these strings are created // without calling intern() method System.out.println(str1 == str2); String str3 = str1.intern(); String str4 = str2.intern(); // Output: true as these strings are created // after calling intern() method on identical strings System.out.println(str3 == str4); } }
Benefits of Using intern() method
- Memory management: By using intern() method, you can save memory as identical strings share the same memory space.
- Faster Comparisons: The strings created using intern() method are called Interned strings, these can be compared using
==
, which is faster thanequals()
method.
Caveats
- Performance issue: If interning is done on large number of strings frequently, it can cause a performance overhead.
- Garbage Collection: The Interned strings are not eligible for garbage collection so they can potentially cause memory leaks if not use correctly.
Practical Use of intern() method.
It can be used in XML parsing or database applications where there are large number of identical strings.
Leave a Reply