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.
equals() method in String class is overriden and it checks for value equality. Then why does following gives false... String s = new String ("abc"; StringBuffer sb = new StringBuffer ("abc"; System.out.println(s.equals(sb)); here value of sb is "abc". Now s.equals(sb) is treated as s.equals(sb.toString())...so both the strings contain the same value. Then Why false ??? Thanx in advance Rashmi
Basically, two objects of different classes are NEVER considered equal. When String's equals() method is called, it will check the run time type of the argument, and if it's not a String, it won't bother to do anything else, it will just return false. Btw, since you brought up StringBuffer, you should know that its equal() method does not override Object's version, so it merely checks for reference equality. Rob [ January 10, 2002: Message edited by: Rob Ross ]
Joined: Aug 07, 2001
Thanx ROB . I know that the strigbuffer class does not override .equals() only string class Rashmi
I'm still a little confused. Rob, you mentioned that the equals() method of the String class will return false if its argument is not of type String. Isn't sb.toString() considered a string at runtime?
Originally posted by Bob Graffagnino: I'm still a little confused. Rob, you mentioned that the equals() method of the String class will return false if its argument is not of type String. Isn't sb.toString() considered a string at runtime?
That's true, that sb.toString() does produce a String, but using s.equals(sb) does not implicity call the toString() method on sb, your StringBuffer. String's equals() method takes an Object as a parameter, so passing it a StringBuffer is fine. However, the first thing the equals() method will do is check the type of the passed parameter to ensure that it's a String. In this case, it isn't, so false is returned. For this to work the way you want, you must explicitly call the toString method on your StringBuffer object, like this:
Corey is right. There are two things the equals method checks and those are whether the passed String is not null && the passed string is an instance of String. If it passes these tests then only it does a comparison otherwise it returns false. Also calling System.out.println(s.equals(sb)); does not call the sb.toString(). I hope this helps!!!
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com