This week's book giveaway is in the OCAJP 8 forum.
We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line!
See this thread for details.
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

Win a copy of OCA Java SE 8 Programmer I Study Guide this week in the OCAJP 8 forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Doubt in equals method" Watch "Doubt in equals method" New topic

Doubt in equals method

sumi selva

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)) {
} else {

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 equals shud retruns true since it has overridden.

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

Srinivasan thoyyeti
Ranch Hand

Joined: Feb 15, 2007
Posts: 557

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

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

I agree. Here's the link:
subject: Doubt in equals method
It's not a secret anymore!