Java Virtual Machine maintains an internal list of references for interned Strings ( pool of unique Strings) to avoid duplicate String objects in heap memory.
Whenever the JVM loads String literal from class file and executes, it checks whether that String exists in the internal list or not. If it already exists in the list, then it does not create a new String and it uses reference to the existing String Object. JVM does this type of checking internally for String literal but not for String object which it creates through 'new' keyword. You can explicitly force JVM to do this type of checking for String objects which are created through 'new' keyword using String.intern() method. This forces JVM to check the internal list and use the existing String object if it is already present.
e.g.
String obj1 = "hello";
String obj2 = "hello";
String obj3 = "hello";
Here we are declaring three String reference variables and in heap one object is created and all the reference variable refer to the same object.
The concept of String Pools is because String objects are immutable.Z
Lets take the previous example code...
If string objects are not immutable and if we changed obj1, say
obj1 = obj1+"world";
This will reflect in all the three reference variables.
Hence because of the immutable property of String Objects we can use the same object to referred by more than one reference variable.
Note: If we are creating String Objects with 'new' keyword , JVM will not check internal String of Pools, and it will create a new heap object.
Comments
Post a Comment