When does the String Literal pool gets cleared?

In one java class I have created this string

String s1 = "abc";

Now if I again use this same statement in a different java class, ie;

String s2 = "abc";

Will I get the same reference for "abc" in both the classes.

Questions by joemonta   answers by joemonta

Showing Answers 1 - 5 of 5 Answers

Yes , they point at the same reference. Check the following code
public class stringreferencetest {

/**

* @param args

*/

public static void main(String[] args) {
// TODO Auto-generated method stub

String s1 = "abc";
AnotherClassString objRef = new AnotherClassString();

if(s1==objRef.s2)
System.out.println("Pointing at same");

else


System.out.println("Not Pointing at same");
}


}

public class AnotherClassString {

String s2="";

public AnotherClassString()
{

s2 = "abc";
}

}

when you run the stringreferencetest class you will get Pointing at same as result

javagek

  • Aug 30th, 2011
 

Yes your would get same reference for both the objects.
String literal pool gets cleared when your JVM exits. String literals are not getting garbage collected ever.

  Was this answer useful?  Yes

adarsh

  • Jul 30th, 2012
 

Code
  1. public class stringreferencetest {

  2.  

  3. public static void main(String[] args) {

  4.  

  5. String s1 = "abc";

  6.  

  7. class AnotherClassString {

  8.         String s2="";

  9.         public AnotherClassString()

  10.  

  11.         {

  12.         s2 = "abc";

  13.         }

  14.         }

  15.  

  16.  

  17.  

  18. AnotherClassString objRef = new AnotherClassString();

  19.  

  20. System.out.println(objRef.hashCode());

  21. System.out.println(s1.hashCode());

  22.  

  23. if(s1==objRef.s2)

  24. System.out.println("Pointing at same");

  25.  else

  26. System.out.println("Not Pointing at same");

  27. }

  28.  

  29.  

  30. }


//Since both have different hashcode, they cant be equal (in this case referencing the same object)please explain if anyone begs to differ

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions