wood burning stoves 2.0
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Equals Method Doubt...... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Equals Method Doubt......" Watch "Equals Method Doubt......" New topic

Equals Method Doubt......

deepu Bhalotia
Ranch Hand

Joined: Apr 19, 2005
Posts: 39
I have created instance of Two Classes.

1. StringBuffer s1=new StringBuffer("Java Ranch");
2. String s2=new String("Java Ranch");

when i use the below given statement, Should it give a compile time error or should return false or true..?


Kedar Dravid
Ranch Hand

Joined: May 28, 2004
Posts: 333
It will return false!
Dhanesh Kumar

Joined: May 06, 2005
Posts: 17

I think it will give false. But I didn’t check it. Why I am saying like this means. The equals methods check both object are meaning fully equal or not if both object are refer the same class. I am assure about it . if it is wrong means … correct me.

deepu Bhalotia
Ranch Hand

Joined: Apr 19, 2005
Posts: 39
You mean to say
Both Wrapper class object should be same and the Value. Other wise it will return false...
Timmy Marks
Ranch Hand

Joined: Dec 01, 2003
Posts: 226
From the javadoc for String:

public boolean equals(Object anObject)Compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.

equals in class Object
anObject - the object to compare this String against.
true if the String are equal; false otherwise.
See Also:
compareTo(java.lang.String), equalsIgnoreCase(java.lang.String)

Since StringBuffer is an Object and not a String, the result is false (true if and only if it is a String of the same sequence of characters.
Sirish Kumar Gongal Reddy
Ranch Hand

Joined: Oct 25, 2004
Posts: 109
i'll clarify you doubt.

1) .equals is used for only to compare secondary datatypes like Objects and Strings.
String s1=new String("javaranch");
String s2=new String("javaranch");
s.o.p("Both are same");
s.o.p("Both are not same");


2) == is used for only to compare primitive datatypes like byte,int,short,long,float and Double.

Getting me ?

G Sirish Reddy.,
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
It will return false, but not for a good reason. An implementation detail (actually, many) has erroneously been specified on the API of java.lang.String and must be maintained forever. Technically (and perhaps more appropriately), the behaviour should return true on most optimal API Specification implementations, but that 'room to move' has been taken away.

Tony Morris
Java Q&A (FAQ, Trivia)
I agree. Here's the link: http://aspose.com/file-tools
subject: Equals Method Doubt......
It's not a secret anymore!