This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
Dear Naveen s3==s4 is false because the string reference s3 & s4 are created using 'new' which always create object in memory separately and that's why it cannot treat it as true. s3.equals(s4) is true because it only compares the string literal therefore it is true. On the other hand, string using '=' sign created in a pool when the other same string is created using '=' sign with same string literal it only points out to the same pool where the first object was available and does not creat another copy in the memory. Therefore s1==s2 is always true cuz it points out to the same string pool where s1 is available. Hope it does not confuse you. Good luck Rashid Ali
1. s1.equals(s2) is true b'cos -> comparing the values of 2 object which is same ie. "amit". 2. s1==s2 is true b'cos -> both have values which is from the same pool of values (where only one copy of "amit" exists). 3. s3.equals(s4) is true b'cos -> see the 1st point. 4. s3==s4 is false b'cos -> the point to 2 different "amit" ( 2 different objects) Hope this helps. Apurba. ------- ------------------ Sun Certified Programmer for the Java 2 Platform
A K<br />Sun Certified Programmer for the Java 2 Platform
String class overrides equals() & hence it does deep comparison to check whether the contents of the two strings under consideration are equal. When you create a String using new operator you actually create a new String at Heap with a distinct memory space. Hence two Strings (S3 & S4) created with new operator reside in different memory locations; i.e their references are different. == operator checks whether the two objects reside in the same memory space; or in other words do they point to the same address;i.e shallow comparison ; & hence you get it false when u compare two distinct strings (S3 & S4)created with new operator. String literals as in the case of S1 & S2 are created in String pool and share the same address as long as the Literal is the same. Hence you get both == & equals() returning true. HTH any comments......Welcome. tvs sundaram [This message has been edited by tvs sundaram (edited July 30, 2001).]
Shallow and Deep comparisons are the two simple ways to understand this concepts. == Shallow equals() Deep When shallow they look only for references match, thats all deep does character by character comparison String does override, the equals() from Object, and the implementation compares it by char. However some wrappers dont, in that case they just inherit equals() from Object which is nuthing but shallow (==) So deep comparison are implementation specific, not a general defacto