• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Where is managed the pool of String?

 
el daniel
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I found this little code based on String.
The are no problems for 1,2, 3,4 but i wonder about the 5!
I thought that Strings litteral were managed in a pool by the class in which they were compiled! In that case 5 would be false as the string litteral " i am unique " belong to different class. But this theory doesn't seem to be correct:-(
So can anybody help me?
public class MyClass{
static String s1 = "I am unique!";
public static void main(String args[]){
String s2 = "I am unique!";
String s3 = new String(s1);
System.out.println(s1 == s2);//1true
System.out.println(s1.equals(s2));//2true
System.out.println(s3 == s1);//3false
System.out.println(s3.equals(s1));//4true
System.out.println(TestClass.s4 == s1);//5true
}
}
class TestClass
{
static String s4 = "I am unique!";
}
 
Basanti Mathad
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey,
String references share the same object(Anonymous object) in the pool when they are created with the same content(not created using new operator).
In your code, though the string is in the other class, it has the same content and so it shares the same anonymous object.
Hope u r clear.
basanti
 
Sarma Lolla
Ranch Hand
Posts: 203
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The pool is not per class. It is per application.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic