Thursday, September 07, 2006

How JVM works with Strings

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.

So the conclusion is, JVM maintains unique String objects for String literals internally. Programmers need not bother about String literals but they should bother about String objects that are created using 'new' keyword and they should use intern() method to avoid duplicate String objects in heap memory which in turn improves java performance. see the following section for more information.

The following figure shows the creation of String Objects without using the intern() method.

You can test the above difference programmatically using == operator and String.equals() method.

== operator returns true if the references point to the same object but it does not check the contents of the String object where as String.equals() method returns true if the contents of the String objects are equal.

s1==s2 for the above code returns true because s1 and s2 references point to the same object.

s3.equals(s4) for the above code returns true because both objects content  is same which is "hello".

You can see this mechanism in the above figure. Here, we have three separate objects which contain same content,"hello". Actually we don't need separate objects because they use memory and take time to execute.

Get more information

Tags: java strings, jvm, objects, heap memory, string.intern, literals

Can't find what you're looking for? Try Google Search!
Google
 
Web eshwar123.blogspot.com

Comments on "How JVM works with Strings"