Inside String Working in JVM
Sunday, July 12, 2009 17:11Java 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.
Have a look at the following code snippet.
String s1 = new String("Java");
String s2 = new String("Java");
System.out.println(s1 == s2);//false
System.out.println(s1.equals(s2));//true
String t1= "JavaSE";
String t2 = "JavaSE";
System.out.println(t1 == t2); //true
System.out.println(t1.equals(t2));//true
String p1 = new String("JavaEE");
p1 = p1.intern();//Forced to use string literal value, from String Pool
String p2 = "JavaEE";
p2 = p2.intern();//Forced to use string literal value, from String Pool
System.out.println(p1 == p2);
System.out.println(p1.equals(p2));
String m = new String("JavaFX");
m = m.intern();//Forced to use string literal value, from String Pool
String n = new String("JavaFX");
n = n.intern();//Forced to use string literal value, from String Pool
System.out.println(m == n);//true
System.out.println(m.equals(n));//true

Evelynn Corridoni says:
May 2nd, 2010 at 9:30 am
hi!, thanks for the information, this post was really useful ! avafx forex broker
Shanna Thomes says:
July 19th, 2010 at 9:43 pm
Foarte bine lucrurile.