Making Efficient Use Of Available Memory With JVM
By: Vaibhav Pandey
Strings are undoubtedly the most important part of any programming language. The same is the case with Java programming Language. Handling String objects in memory is a demanding task. One of the key goals of any good programming language is to make efficient use of available memory. As the size of our application grows the size that string literals occupy also becomes larger. Sometime memory may overflow due to high number of string literals used. There may be literal redundancy in the memory. In case of Java programming Language JVM does all memory related tasks specially related with Strings.
In Java JVM sets up a special Sting memory area called ” String Constant Pool “. Whenever Compiler encounters a String literal it checks to see if there is an identical String already exists. If the String exists then the reference is directed towards existing literal else new String literal object is created.
The important property of Strings is that they are immutable. Yes,you cannot change them. Once you have created a string its unchangeable. You can only assign a new value to the existing String reference,and what happened to previous string as usual it is lost. Lets see what actually happens consider following program:-
String s=”abcd”;
s=s+”efgh”;
System. out. println(s);
In this case the output would be ‘ abcdefgh ‘. In the process of getting this value the JVM has actually 3 string literals
1. abcd
2. efgh
3. abcdefgh
In order to get the result abcdefgh we have lost the two strings. But point to be noted here is that they remain in memory because the reference is now pointing to some other string and it is considered as lost. There is no way we can refer this string in practical.
Now we can start to see why making string objects immutable is such a good idea. If several reference variables refer to the same string without even knowing it,it would be very bad if any of them could change the strings value.
You might say if somebody overrides the String class functionality then what will happen,couldn’t that cause problem in the pool??? Well the language designers were well aware about it and that is why they marked String class as ‘ final ‘. Means nobody cannot ever override the String class functionality. So that you can assure yourself about String objects because they are immutable.
JVM on the other hand does garbage collection that is it periodically checks for dangling references on the string literals and on other constants. Whenever one is encountered JVM sweeps it from the memory pool. You have methods to force JVM for garbage collection but mind you it is not a human its a die hard computing machine the JVM thus it does garbage collection when it suits otherwise it keeps mum.

