This week's book giveaway is in the Agile and other Processes forum. We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line! See this thread for details.
Hey, I had joines the ranch recently and i had started appreciating the collective effort that is beeen put on.. Cheers!! Cansomebody enlighten me on the difference between == and equals method with respect to String. Thanks Subbu
Subbu
Mary Anitha
Greenhorn
Joined: Oct 13, 2000
Posts: 23
posted
0
== is used to check whether the object-references point to the same object equals() is used to compare the contents of the objects i.e. the strings eg: String s1 = new String("java"); String s2 = new String("java"); System.out.println(s1 == s2); //result is false System.out.println(s1.equals(s2)); // result is true
mana
Greenhorn
Joined: Oct 15, 2000
Posts: 4
posted
0
hi friends, In the foll. code 1.StringBuffer sb1 = new StringBuffer("Amit"); 2.StringBuffer sb2= new StringBuffer("Amit"); 3.String ss1 = "Amit"; 4.System.out.println(sb1==sb2); 5.System.out.println(sb1.equals(sb2)); 6.System.out.println(sb1.equals(ss1)); 7.System.out.println("Poddar".substring(3)); shouldn't the 6th line give compile error as equals method is not overriden in stringbuffer class.can anybody please explain. thanks, mana
Surya Bahadur
Ranch Hand
Joined: Sep 28, 2000
Posts: 88
posted
0
Hi mana Every class extends object and StringBuffer is no exception,but it does not override the equals method from the object class,it just inherits it. Surya
Kav Bop
Greenhorn
Joined: Sep 28, 2000
Posts: 7
posted
0
Hi! Mary Anitha is correct when she mentioned the difference between == & equals(). I would like to elaborate a bit more on this one. In the class Object, equals() method behaves similar to the == operator. i.e. equals() returns true only if this == object reference of parameter All available classes in java override the equals() method to compare the contents. However, if you write your own class (by default it inherits from Object), the behaviour of equals() will be same as that of ==, unless you override equals() to compare contents rather than refernces. I hope the above clears the difference between == & equals(). One point to remember is equals() method always check the types of the invoking object & the parameter passed. If the types are not the same, it returns false, no matter what the contents. Only if the types match, it goes for checking the contents. [This message has been edited by Kav Bop (edited October 16, 2000).]
Kavita
Ajith Kallambella
Sheriff
Joined: Mar 17, 2000
Posts: 5782
posted
0
'Subbu C', PROPER NAMES ARE NOW REQUIRED!! Read this post for more details. Ajith
Open Group Certified Distinguished IT Architect. Open Group Certified Master IT Architect. Sun Certified Architect (SCEA).