String interning – Storing only one copy of each distinct String value
It is a process by which String object is moved to String Pool
String can be created by 2 ways
- String literal –> String car = “Bmw”;
- String object –> String bike= new String(“ThunderBird”);
Java maintains a pool of interned string object references. When the intern() is called on a String object , the pool is checked if a string object with the same value exists. If it does then the reference of the existing object is returned. Else a new object is created and its reference is added in to the intern pool.
String literal
- String created using String literal are automatically interned
- It is stored in Permanent generation memory area.
- car object will be created,its reference will be stored in String pool and it will be automatically interned
- String car1=”Bmw”;String car2 = “Bmw”;
- car1 = =car2==car3. All three will be pointing to same object
String Object
- String created using new object should be explicitly interned
- They will be stored under Java Heap Memory
- String bike1= new String(“ThunderBird”);String bike2= new String(“ThunderBird”);
- bike,bike1 & bike2 will be pointing to 3 different string objects in Java Heap Memory
- To make them point to same object they need to be interned explicitly
- String bike4 = bike.intern(); This will first check if there is a object in String pool with the same value . Since bike is originally created in Java heap memory it will return false as it is not available in the String intern pool. Now it will create a object in the String pool and return the reference
- Now if we check if bike4 == bike it will return false. Because bike4 is in string pool and bike is in object pool
- To avoid this we need to do something like this; String bike = new String (“ThunderBird”);bike = bike.intern();
Things to note
- s1.intern() == s2.intern() only if s1.equals(s2)
- For interned strings we can use == for comparison as we know that value of its references will always be the same.
- Use interned strings when your usecase involves lot of string comparison. Using == is much faster then .equals() method.
- Mostly used in HashKey comparison.
- Saves space as multiple copy of same string will be pointing to the same object.
Dis-advantages
- Remember to intern all string objects that would be compared
- Maintains a pool of interned Strings
- Creation time increases as it compares against the interned pool before allocating the reference.
- Pre-Java7 Intern pool is maintained in Permanent Gen Mem area which has the restriction on size, which can lead to OutOfMemoryError:PermGen Space
- From Java 7 onward it is moved to Java Heap Memory
Advertisements