s1==s2 returns true, if bothe the references (s1,s2) ae aliases (referes to same object)
class
Test {
public static void main(String args[])
{
String s1="abcd"; //line1
String s2="abcd"; //line2
String s3=new String(s2);//line3
String s4= new String("abcd");//line4
System.out.println(s1==s2);//line5
System.out.println(s1==s3);//line6
System.out.println(s1==s4);//line7
System.out.println(s3==s4);//line8
}
}
output
true
false
false
false
line1-// a string object "abcd" is created in string pool
line2-// here another string object without using new operator is created so the reference of "abcd" (in string pool) will be given to s2.here s1, s2 are aliases, means pointing to same string object.
****** If 'new' keyword is used to create a new object , then that object is diffent object *********
lines3// here s3 object is created using s2, 'new' keyword is used . so s2, s3 are two different objects, but having same string content. here equals method returns true (contents), == returns false ( not same objects)
line4// a new object s4 is created.
line5// s1,s2 are created with out using 'new' keyword, == returns true ( s1,s2 refers to same string placed in string pool )
line 6// s3 is created using new keyword. so contents are same but objects are different. so == returns false.
line7// s4 is created using new keyword. ..............
line 8 // s3, s4 two different objects so == returns false.
try the same code with equals method as well as == operator for better understanding. Replace all String objects with StringBuffers and run the code.
Hope this helps u
Regards
Naresh
[ December 16, 2005: Message edited by: Naresh Kumar ]