How to demonstrate working of intern() method in String class through a example ?.

Program to demonstrate working of intern() method in String class through a example.

package com.hubberspot.examples;

public class InternDemo {

 public static void main(String[] args) {

  // Using new String() each time the line 
  // executes a new instance is created
  // Avoid this kind of usage of String
  // creation
  String name1 = new String("Hubberspot");

  // String instance should be created by 
  // below statement. It maintains and avoids
  // new creation of instance each time 
  // the line gets executed.
  String name2 = "Hubberspot";

  // Before calling intern() method lets test reference value
  // equality of both name1 and name2 String objects.
  if(name1 == name2){

   System.out.println("Before calling intern() : name1 == name2 is true");

  }
  else {

   System.out.println("Before calling intern() : name1 == name2 is false");

  }

  // Whenever an String object is created by using new operator
  // always a new object gets created in the heap whether 
  // it has same value or not. 
  // Whenever an String object is created by using "" a constant
  // string object gets created in the heap memory.
  // The difference is shown by above example i.e before calling
  // intern() method.

  // When the intern method is invoked, if the pool already 
  // contains a string equal to this String object as determined 
  // by the equals(Object) method, then the string from the pool 
  // is returned. Otherwise, this String object is added to the 
  // pool and a reference to this String object is returned. 
  name1 = name1.intern();

  // After intern method gets executed name1 is added to the 
  // String constant pool and reference is returned back to 
  // name1.
  // Below results shows the variation in the result ... 
  if(name1 == name2){

   System.out.println("After calling intern() : name1 == name2 is true");

  }
  else {

   System.out.println("After calling intern() : name1 == name2 is false");

  }
 }
}



Output of the program :