File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Equals confusion

 
kavin kumar
Greenhorn
Posts: 22
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
Posts: 262
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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'"
 
Dharmesh Gangani
Ranch Hand
Posts: 30
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
//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.
 
sateesh Boganadham
Greenhorn
Posts: 1
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 101
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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]
 
kavin kumar
Greenhorn
Posts: 22
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks so much !

Iam all clear now
 
Don't get me started about those stupid light bulbs.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic