Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Can someone explain how this code works?

 
Joey Chen
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


I'm trying to figure out how this code results in a number of 24 at the end... Part of the reason I really don't understand how it arrives at 24 is I don't really understand how "Echo e2 = e1;" works. Can someone clarify that? I'm assuming object reference e2 takes on the same values as e1?
 
Raghavan Muthu
Ranch Hand
Posts: 3381
Mac MySQL Database Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To your query,


I don't really understand how "Echo e2 = e1;" works. Can someone clarify that? I'm assuming object reference e2 takes on the same values as e1?


Yes. once you say e2=e1, the object referred by the reference variable e1 is assigned to the reference variable e2 as well.

After the execution of this statement, both the reference variables e1 and e2 will be pointing to the same object thereby resulting a reflection on the same object irrespective of the reference variable through which you proceed.

HtH.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12185
34
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
your variables e1 and e2 are really both pointers to objects. they're like pieces of paper with your bank account number on them.

so when you say "Echo e2 = e1", your saying "give me a new piece of paper with same bank account number written on it as is written on that first one."

so now, you have two slips of paper, both referring to the same account. so, any time you use EITHER one to add a dollar to your account, the SAME account gets more money.
 
Joey Chen
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Fred Rosenberger:
your variables e1 and e2 are really both pointers to objects. they're like pieces of paper with your bank account number on them.

so when you say "Echo e2 = e1", your saying "give me a new piece of paper with same bank account number written on it as is written on that first one."

so now, you have two slips of paper, both referring to the same account. so, any time you use EITHER one to add a dollar to your account, the SAME account gets more money.


Thanks, great explanation!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic