aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Doubt in equals method 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 "Doubt in equals method" Watch "Doubt in equals method" New topic
Author

Doubt in equals method

sumi selva
Greenhorn

Joined: Jul 10, 2007
Posts: 19
Hi, I executed the following code and got the output as : success
I could not understand the output.since we call the equals method of the object class, which is not overriden.It should return Failed.But why does it gives success as output.could anyone explain me clearly about the equals.

public static void main(String[] args) {
String s = new String("hi");
Object o = new String("hi");
if(o.equals(s)) {
System.out.println("success");
} else {
System.out.println("Failed");
}
}

If the lines has been
String s1 = new String("hi");
String s2 = new String("hi");
then it means only one string obj is created and both s1 ans s2 refer to it.so equals shud retruns true since it has overridden.

But in the above example, we call the equals on object class which does not override equals..so actually two objects are created.but how come it retirns that they are equal?

Thanks,
Sumi
Srinivasan thoyyeti
Ranch Hand

Joined: Feb 15, 2007
Posts: 557
sumi,

You did n't get OO concept Polymorphism.

Object o = new String("hi");

when we call o.eqauls() equals of String is is executed.


Take this example:



Thanks & Regards, T.Srinivasan
SCWCD 1.4(89%), SCJP 5.0(75%)
sumi selva
Greenhorn

Joined: Jul 10, 2007
Posts: 19
Hi,
Thank you very much.Now got cleared.

Thanks,
Sumi
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Doubt in equals method