• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Devaka Cooray
  • Knute Snortum
  • Paul Clapham
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Bear Bibeault
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Ron McLeod
  • Piet Souris
  • Frits Walraven
Bartenders:
  • Ganesh Patekar
  • Tim Holloway
  • salvin francis

equivalence  RSS feed

 
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Given the following code:

Why it will print out "Objects have different values"? Thanks for any inputs.
Luk
 
Ranch Hand
Posts: 68
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Each time you use new, Java construct a NEW object and allocate memory for it. So the reference a and b point to different objects on the memory heap. The equals method in Object only returns true if and only if the two references refers to the same object.
To compare the object content you have to override the method. For example, String object has its own equals method that compares the character sequence of two strings rather than if the two String references point to the same object on the heap.

 
luk Hann
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, huiying. Excellent explanation!
Luk
 
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Luk Hann
After you get yourself aquainted with the concept of object equivalence , you may take the following self evaluation questions.
http://www.tipsmart.com/javacert/selfreview/objequiv.htm
Understanding this concept is crucial for learning Java as well as from SCJP standpoint.
-Sandeep Nachane
 
luk Hann
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, Sandeep,
Thanks for your recommendation. The quiz is really good and I actually took the quiz before asking the questions here. I got completely confused with the operator == and method equals() after taking the quiz (plus other questions in this topic from Ablahish's Java Quiz). For example, I couldn't understand Q5 & Q10 as well as a couple of other questions in tipsmart's quiz.
I really wonder what's the rule of thumb here to deal with those questions. Since I am goint to take the exam next week, and it is my pain in the neck still geting confused with it so far! Someone please help me out on this topic and I highly appreciate it!
Luk
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!