Win a copy of Java Mock Exams (software) this week in the Programmer Certification (OCPJP) forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Doubt in equals method

 
sumi selva
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 558
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:

 
sumi selva
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Thank you very much.Now got cleared.

Thanks,
Sumi
 
Happiness is not a goal ... it's a by-product of a life well lived - Eleanor Roosevelt. Tiny ad:
the new thread boost feature: great for the advertiser and smooth for the coderanch user
https://coderanch.com/t/674455/Thread-Boost-feature
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!