• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

equivalence

 
luk Hann
Ranch Hand
Posts: 48
  • 0
  • 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
 
huiying li
Ranch Hand
Posts: 68
  • 0
  • 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
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, huiying. Excellent explanation!
Luk
 
Sandeep Nachane
Ranch Hand
Posts: 57
  • 0
  • 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
  • 0
  • 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
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic