In this article, we are going to look at when and how to use String's intern() operation.
Contents
- When to use String's intern() operation
- How to use String's intern() operation
Strings in java are special type of data type, they are immutable, meaning once created, they cannot be changed and if we try to change them, that results in a new string.
It stores the strings into a special place in JVM memory called String pool (but not always!),
it really depends on how you create the string.
For example, if you want to create a string str = "Hello", Let's look at some ways of creating this:
String str = "Hello";
String str = new String("Hello");
The advantage with String pool is that, it re-uses the strings from the pool if the values are same
instead of creating new ones each time there is a need, but if the object is created using new
,
then it will create Strings as objects just like any other objects, and if the strings are ever created using new
keyword
and you want to move it string pool if strings that your application using are repetitive, we can use String.intern() method.
Starting from Java 7, string pool is part of JVM heap and prio to that it was part of PermGen space.
With the recent JVM versions after Java 7, the advantage is that if the memory is approach its limit, strings that are no longer needed will get garbage collected, earlier with PermGen space this was not the case.
We can call String.intern() inbuilt native method, on the string that was created using new
keyword to move it to string pool.
For example, in the below example Strings s1 and s2 both have same values "Hello",
and if you check whether they are pointing to same reference or not, s1 == s2, it will return false,
but after we call intern() on s2, then they will point to same reference inside JVM.
public class StringIntern {
public static void main(String[] args) {
String s1 = "Hello";
String s2 = new String("Hello");
System.out.println("Before interning - are strings s1 and s2 are using same JVM reference ? : "+ (s1 == s2));
String s3 = s2.intern();
System.out.println("After interning - are strings s1 and s2 are using same JVM reference ? : "+ (s1 == s3));
}
}
When you run the above program, you will get the below output.
Before interning - are strings s1 and s2 are using same JVM reference ? : false
After interning - are strings s1 and s2 are using same JVM reference ? : true
Above example complete source code can be found at Github