The JVM set a pool in the memory for string to make memory more efficient that is called string constant pool.
Whenever compiler found a String literal (i.e. "hello", "good morning") then it check the pool whether same String exists or not. If a match found then it will return the reference of it, otherwise it will create a new string in the pool.
String s1="hello"; // create one object in string constant pool
Can you guess? how many objects are created in the following statement...
String s2= new String("welcome");
it will create two objects - one in string constant pool, second one in normal memory.
public class Test{
public static void
main(String[] args) {
String s1="hello";
String s2="hello";
//both reference refer to same instance of String
System.out.println(s1==s2);
String s3=new String("hello");
//s3 refer to new instance of String
System.out.println(s3==s2);
//content of s3 and s2 are same
System.out.println(s3.equals(s2));
}
}
Tuesday, November 24, 2009
Subscribe to:
Posts (Atom)