For example, when you create a String literal like "ABC" then it's automatically stored in String pool, but when you create a new String object, e.g. new String("abc"), even though it's the same String, a new object at a different memory location is created. This is a duplicate String.
By calling the intern() method on this object, you can instruct JVM to put this String in the pool and whenever someone else creates "abc", this object will be returned instead of creating a new object.
This way, you can save a lot of memory in Java, depending upon how many Strings are duplicated in your program.
Some important things about String.intern() method
Here are some of the important points about the intern() method from java.lang.String class which is worth remembering:
1) The String.intern() method is there in the String class from JDK 1.1. It returns a canonical representation of String object. When the intern method is invoked, if the String pool already contains that String object such that equals() return true, it will return the String object from the pool, otherwise it will add that object to the pool of unique String.
2) After calling intern() method on s1 and s2, s1.intern() == s2.intern(), if s1.equals(s2) because both will be pointing same String constant in pool.
3) Prior to Java 6, uncontrolled usage of String.intern() method can cause java.lang.OutOfMemory: PermGen space because String pool was physically located on PermGen area of Java heap, which is quite small in many JVM (32M to 96M) and fixed.
From Java 7 onward, the intern() method has become even more useful because the String pool is relocated to the main heap space of JVM.
This will help to further reduce String duplication by using String.intern() method.
In the below diagram you can see that s3 and s4 are referring to the same String object "java" in the String pool because they are interned String while s1 and s2 are referring to separate object because they are not interned or not using String literal.
4) Another thing to know about is that the intern() method is a non-static method and should be called using a String literal or String object in Java.
0 comments:
Post a Comment