Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Regarding reference variable

 
kannan vinayagam Duraiswamy
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Code 1 :


In the above program the reference variable 'a' is added to the list 'l'.
So when processing the list, the list return the 'reference' which points the value "a".
Q : am i right?.
Then,
code 2 :


here the reference variable 'a' is reused again at line 1.
i.e., pointing the reference variable 'a' to a value "b" or else to a new string object "b".
again i add the reference variable to the list 'l'.

at last the list 'l' has two (same)reference variable.
so while processing the list 'l', how did the first value "a" is retrived as the reference varaible 'a' is pointed to a new string object "b" ?.



 
amitabh mehra
Ranch Hand
Posts: 98
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think its because the actual object is added to the list and not the reference that points to that object.
 
kannan vinayagam Duraiswamy
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i.e, the 'object' are stored in the list not the 'reference variable' .

 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the above program the reference variable 'a' is added to the list 'l'.


No. Java is pass by value, so a copy of the reference variable is added to the list. After the call to list.add, there will be two references to the String - 'a' and the one in the ArrayList.

Armed with that knowledge, what is happening in the rest of the program should now make sense. Let us know if it doesn't.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic