• Post Reply Bookmark Topic Watch Topic
  • New Topic

How pass by value works? [Reversing LinkedList]  RSS feed

 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
After reading more than 70% of Kathy Sierra's book I thought I get how most of the fundamental concepts work in Java. BUt I am baffled by how the code below is behaving

I am trying to reverse a singly linkedlist iteratively.


Code For linkedlist reversal:


The ouput is:



The problem is at line number 39 root = prev;. The variable gets the reference to only in the function. When the function gets back to the calling function I assumed since root is an object reference variable it will still hold the reference the reference to prev. But apparently, it doesn't.
Can someone help me understand this concept better? I thought object reference variables retain the references assigned to them in the called function even when the execution goes back to the calling function.



Here is the helper LinkedList class:




 
Sheriff
Posts: 4289
127
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Java always passes arguments by value.  Always.  So it passes object references by value.  But because the copy of the object reference can dereference the object's methods, you can do this:

This will set the name in obj and that change persists after the method returns.  What you can't do is this:

obj is a copy of the object reference.  You are changing the obj's reference, but this is only a copy, so it doesn't persist after the method returns.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!