Java Provides a technique for String Objects:

  • String objects using String.intern() method to forces JVM to check the internal list and use the existing String object if it is already present.
  • JVM maintains unique String objects for String literals internally
Example
/* This Program is make to understand the intern() method */ 
package StringProject;
public class Class1 {
  public static void main(String[] args) {
    /* making String Objects with value Hello */
    String s1 =new String("Hello");
    String s2= new String("Hello");
    System.out.println("First String "+s1);
    System.out.println("Second String "+s2);
    /* Check both Strings are (== ) */
    System.out.print("s1==s2 ?");
    System.out.println( s1==s2);
    /* check both Strings are (equal()) */
    System.out.println("s1.equals(s2) ?" + s1.equalsIgnoreCase(s2));
    System.out.println("After intern() method==");
    /* calling of intern() method */ 
    s2=s2.intern();
    s1=s1.intern();
    /* After intern() calling check String(==) */
    System.out.print("s1==s2 ?");
    System.out.println( s1==s2);
    /* After intern() calling check String(equal()) */
    System.out.println("s1.equals(s2) ?" +     s1.equalsIgnoreCase(s2));
  }
}

OUTPUT
String Performance Output
After Interning the String Object:
String Object After Intern

String Literal and String Object Performance

Example
OUTPUT
/* This Program is Mainly for check the performance of both String Literals and
 String Objects */ 
package StringProject;
public class Class1{
   public static void main(String[] args){
   System.out.println("Optimized Time Taken By String Literals and String Objects:");
    /* To check performance */ 
    long strttime1=System.currentTimeMillis();
    /* Making String Literals */
    for(int i=0;i<500000;i++)
    {
      String s1 ="Hello";
    }
    long endtime1=System.currentTimeMillis();
    System.out.println("For String Literals Time Taken:"+(endtime1 - strttime1));

    long strttime2=System.currentTimeMillis();
    /* Making String Object */
    for(int i=0;i<500000;i++)
    {
      String s2 =new String("Hello");
    }
    long endtime2=System.currentTimeMillis();
System.out.println("For String Objects Time Taken:"+(endtime2-strttime2));
  }
}
OUTPUT
String Performance Output