s1.equals(s2);//ok s3=s1.intern(); s4=s2.intern(); if(s3==s4)//ok But if i do:- if(s1==s3)//not ok(not refer to same object); if(s2==s4)//not ok when String method intern is invoke on the String object,it return a reference to a String object that is guaranteed to have the same contant,However,String s1 and String s2 have the same contents,the reference returned by this call to intern is a reference to the String object returned by s1.intern() and s2.intern().But s1==s3 and s2==s4 give that they are not refer to same object,Why?;
s1 = new String("hello") creates a String object with "hello" as the value and enters "hello" into the string literal table. s2 = new String("hello") also creates a String object with "hello" as the value, "hello" is already in the literal table, no entry made. As s1 and s2 are different objects: (s1 == s2)==false s3 = s1.intern() gets the "hello" string object from the literal table and assigns it to s3. s4 = s2.intern() also gets the "hello" string object from the literal table and assigns it to s4. s3 and s4 have reference to the same object, so (s3 == s4) == true. It helps me to remember that s1 (for instance) is a reference to a String object, not the object itself. given that, (s1==s3) doesn't ask 'is s1 equivalent to s3?' but rather 'is the object that s1 refers to the same object as s3 is referring to?' if you were to change s1 = new String("hello") to s1 = "hello", then (s1==s3) would == true, because s1 = "hello" both creates a string object and assigns that same object to s1 and the literal table, which would also be assigned to s3 at: s3 = s1.intern() Does that help?
Note to SCJP candidates: For the exam, it is very important to understand String immutability, and it is important to understand == vs. the equals() method. But just so no one wastes any time, the intern() method itself is NOT on the exam. Thanks, The Focus Police
Spot false dilemmas now, ask me how!
(If you're not on the edge, you're taking up too much room.)