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

Equals confusion

kavin kumar
Greenhorn

Joined: Jul 21, 2005
Posts: 22

I had the same kind of question in Kathy sierra book. But i dont understand their explanation. Plz help me with this.

I think (s2 == o ) should return false;
since they r refering to 2 different objects.
Correct me if iam wrong ?Explain me why?

Thanks in advance
Kavin
[ August 16, 2005: Message edited by: Mark Spritzler ]
Dave Wingate
Ranch Hand

Joined: Mar 26, 2002
Posts: 262
Because ....

//line2
Object o = s2;


The pointers "o" and "s2" now point to the same object. The line above can be read as "Let 'o' point to the same object pointed to by 's2'"


Fun programming etcetera!
Dharmesh Gangani
Ranch Hand

Joined: Feb 20, 2004
Posts: 30
//line2
Object o = s2;

The line means Object o will point to the same reference to which s2 is pointing. So (s2 == o) will return since both the objects are pointing to the same reference.


-=-=-=-=-=-=-=-=-=-<br />Thanks & Regards,<br />Dharmesh G.
sateesh Boganadham
Greenhorn

Joined: Mar 29, 2005
Posts: 1
Hi,

The semantic meaning of the equals method defined in java.lang.Object class is as follows:

The method gonna return true if both the references are pointing to the same object, (although the references are not from the same class, but are compatible)....

So in the above program all the three if becomes true resulting in printing of 1 2 3 in that order.
Esam Ahmed
Ranch Hand

Joined: Aug 10, 2005
Posts: 101
When == is applied to object references, it looks for object reference equality not object value equality.

But when == is applied to primitive types, it looks for primitive value equality.

Thus when we declared: //line1 str2 s2 = new str2();

and made the assignment: //line2 Object o = s2;

As everybody said: we assigned the reference ( s2 ) to the reference o .

Now, references o and s2 are aliases.

Also, since any class implicitly inherits (if no extend clause is used) from the class Object, it is always possible to upcast the object reference of this class to that of class Object.

So the assignment: Object o = s2; is valid.

And since, the reference values are the same, it returns true.

Hope I am clear.



Esam. [/LIST][/LIST]


Esam<br />SCJP 1.4, SCWCD 1.4
kavin kumar
Greenhorn

Joined: Jul 21, 2005
Posts: 22
Thanks so much !

Iam all clear now
 
 
subject: Equals confusion