Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 11 of 11

Thread: Pass-by-Value scheme, puzzled with passing/assigning a reference to another object

  1. #1
    Java kindergarten chronoz13's Avatar
    Join Date
    Mar 2009
    Location
    Philippines
    Posts
    659
    Thanks
    177
    Thanked 30 Times in 28 Posts

    Default Pass-by-Value scheme, puzzled with passing/assigning a reference to another object

    i just encountered a strange thing with object reference as i was creating my own linked list,

    The main class
    public class WordLinkedListSampleProgram {
     
        public static void main(String[] args) {
     
            WordLinkedList nL = new WordLinkedList();
     
            nL.addValue("A");
            nL.addValue("B");
     
            nL.reversedLink();
        }
    }

    The WordLinkedList class
    public class WordLinkedList {
     
        private Node start;
        private Node next;
        private Node last;
        private int listSize;
     
        public void addValue(String val) {
     
            if (listSize == 0) {
     
                start = new Node(val);
                next = start;
                start.setNext(next);
            }
            else {
     
                next.setNext(new Node(val));
                last = next.getNext();
                next = last;
                last.setNext(null);
            }
     
            listSize++;
        }
     
        public void reversedLink() {
     
            Node tempStart, tempNext;
     
            tempStart = last;
            tempNext = tempStart;
            // tempStart.setNext(tempNext);
     
            // i was expecting this part should throw a null pointer exception,
            // but if the above statement tempStart.setNext(tempNext); is UNCOMMENTED
            // this statement doesnt throw any exception even with more .getValue() consecutive calls
            System.out.println(start.getNext().getNext().getValue());
        }
    }


    The Node class
    public class Node {
     
        private Node nextNode;
        private String value;
     
        public Node(String val) {
     
            value = val;
        }
     
        public Node getNext() {
     
            return nextNode;
        }
     
        public void setNext(Node n) {
     
            nextNode = n;
        }
     
        public String getValue() {
     
            return value;
        }
    }

    base on what i know so far is, the local 'tempStart' affects the reference of the data member 'last'?
    what i know is, this kind of reference control is only possible with java arrays
    how come it happens with data fields and objects?

    the data member 'last''s references should not be affected when i pass it in another variable.. how come in my case it does?
    am i missing something?

    please correct and enlighten me, thank you in advance. any help would be greatly appreciated


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Pass-by-Value scheme, puzzled with passing/assigning a reference to another objec

    Can you post the print out that show what you are talking about? Add printlns as needed to show the problem and add some comments to the print out describing what is wrong and show what the output should be.
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Java kindergarten chronoz13's Avatar
    Join Date
    Mar 2009
    Location
    Philippines
    Posts
    659
    Thanks
    177
    Thanked 30 Times in 28 Posts

    Default Re: Pass-by-Value scheme, puzzled with passing/assigning a reference to another objec

    on the main class i had a two nodes linking to each other, so it is the start and another node that this node is pointing at.
    On the method call .reverseLink(), there is a statement that prints the value of each node.

    this code shows how the value of each node is printed,
    // this one prints "B", as it is the next node that the start is pointing to
    System.out.println(start.getNext().getValue());
     
    // if i change it into
    System.out.println(start.getValue()); // this will print "A" as it is value



    on the second code(WordLinkedList class),
    the statement
    System.out.println(start.getNext().getNext().getValue());
    should throw a null pointer exception, it points out to a third node which doesnt exist. so im definitely expecting a null pointer exception



    but i am puzzled with this statement
     tempStart.setNext(tempNext);




    if this code is NOT commented, the statement
    System.out.println(start.getNext().getNext().getValue());
    doesn't anymore throw a null pointer exception, but with removing it or commenting it, it throws the expected error that i assume




    the exception points out to the print statement
    Exception in thread "main" java.lang.NullPointerException
    	at Chapter16MemoryAllocationSchemesAndLinkedDataStructures.Exercises.WordLinkedList.reversedLink(WordLinkedList.java:48)
    	at Chapter16MemoryAllocationSchemesAndLinkedDataStructures.Exercises.WordLinkedListSampleProgram.main(WordLinkedListSampleProgram.java:20)
    Last edited by chronoz13; June 1st, 2012 at 10:24 AM.

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Pass-by-Value scheme, puzzled with passing/assigning a reference to another objec

    tempStart.setNext(tempNext);
    You need to look at what the code is doing. What does the above statement do to the list?
    What are the values of the two variables?

    One good technique I use for debugging linked lists is to add a toString() method to the Node class that returns the value and the link:
    return "Node: " + value + " next=" +nextNode;

    Then you can print a node variable to see its value and the link to next.
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Java kindergarten chronoz13's Avatar
    Join Date
    Mar 2009
    Location
    Philippines
    Posts
    659
    Thanks
    177
    Thanked 30 Times in 28 Posts

    Default Re: Pass-by-Value scheme, puzzled with passing/assigning a reference to another objec

    that is what confuses me, please let me do my best to explain it further.
    in the whole program, i got a linked-list with 2 nodes

    start - as the first one, set to next(another node)
    last - is the last node/another node(i.e the next node the start is pointing at)
    last does not point to any node anymore, so it has a null 'nextNode' inside of it
    so if there is a call like last.getNext(); it should throw a null, or a start.getNext().getNext(); should throw a null or a last.getNext().getNext() should throw a null exception as well , that is basically what i am expecting to happen because i only have a 2 nodes linked to each other

    im so puzzle that why this following statements doesnt throw a null
    exception, any of these should throw a null
    start.getNext().getNext()
    // or 
    last.getNext()
    // or
    last.getNext().getNext()

    with printing the values of the nodes,
    printing values.. like these calls
    last.getNext().getValue(); // prints "B"
    last.getNext().getNext(); // prints "B"
    last.getNext().getNext().getNext(); // still prints "B"
    all of which should throw a null exception when the statement..

    tempStart.setNext(tempNext);
    is commented or removed


    if not, every node starting from 'start' to 'last' is being affected, last.getNext()/start.getNext().getNext() should never have any more nodes to call(a null exception should be thrown), but with those local variable NODES(temp nodes), Im totally mystified why the data member nodes are affected.. and just like what i've said, my assumption was the reference of 'last' data member is being affected when that code above is uncommented

    my expectation is even that code is there or not, last.getNext() or start.getNext().getNext() should always throw a null, but why doesnt it?

    my goal was to reverse the links, i was able to do so, by making a doubly-linked list(i.e with a set previous and a set next nodes), but i wanna get ahead of this one, as this is one of the crucial things that i need to deal with java references, i even got another one like this, but i might be able to understand it by just getting ahead of this one. please ask me and im willing to explain it as possible as i can.. thanks again norm.

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Pass-by-Value scheme, puzzled with passing/assigning a reference to another objec

    tempStart.setNext(tempNext);
    Do you see what that statement is doing?
    Have you taken a piece of paper and drawn the linked list and manually drawn in what that one statement does?

    Did you add the toString method I mentioned so you can print out the nodes and easily see the state of the list?
    If you don't understand my answer, don't ignore it, ask a question.

  7. #7
    Java kindergarten chronoz13's Avatar
    Join Date
    Mar 2009
    Location
    Philippines
    Posts
    659
    Thanks
    177
    Thanked 30 Times in 28 Posts

    Default Re: Pass-by-Value scheme, puzzled with passing/assigning a reference to another objec

    yes i put a toString() in the Node class but it throws a StackOverFlow error, pointing at the toString() method itself,
    and i made a call on the toString() inside the reverselink method .print(last.toString) or .print(tempStart.toString);
    Exception in thread "main" java.lang.StackOverflowError
    	at java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:391)
    	at java.lang.StringBuilder.append(StringBuilder.java:119)
    	at xUnfinished_Errorsx.WordNode_UC.toString(WordNode_UC.java:38)
    	at java.lang.String.valueOf(String.java:2826)
    	at java.lang.StringBuilder.append(StringBuilder.java:115)
    	at xUnfinished_Errorsx.WordNode_UC.toString(WordNode_UC.java:38)




    yes i manage to track down what this statement does with the local node
    tempStart.setNext(tempNext);

    because of these first 2
    tempStart = last;
    tempNext = tempStart;
    the tempStart is just pointing to itself, somehow it becomes a dog chasing its own tail...


    thats why this statement
    System.out.println(tempStart.getNext().getNext().getValue());
    clearly shows that tempStart.getNext() or more call to .getNext() is just calling its ownself thats why it never throws a null pointer exception

    but this one still confusing me, i cant track it down. considering its a data member just passing its reference to a local one
    System.out.println(last.getNext().getNext().getValue());
    how it is being affected with the statement tempStart.setNext(next);
    how come the 'last' points it self to itself.

  8. #8
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Pass-by-Value scheme, puzzled with passing/assigning a reference to another objec

    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  9. The Following User Says Thank You to KevinWorkman For This Useful Post:

    chronoz13 (June 2nd, 2012)

  10. #9
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Pass-by-Value scheme, puzzled with passing/assigning a reference to another objec

    somehow it becomes a dog chasing its own tail...
    That's why you get the stack overflow. next goes to next goes to next forever.
    To keep toString() from going forever, change it to return this:
          return "Node: " + value +  " next=" + (nextNode == null ? null : nextNode.getValue());
    If you don't understand my answer, don't ignore it, ask a question.

  11. The Following User Says Thank You to Norm For This Useful Post:

    chronoz13 (June 2nd, 2012)

  12. #10
    Java kindergarten chronoz13's Avatar
    Join Date
    Mar 2009
    Location
    Philippines
    Posts
    659
    Thanks
    177
    Thanked 30 Times in 28 Posts

    Default Re: Pass-by-Value scheme, puzzled with passing/assigning a reference to another objec

    @KevinWorkMan thats what i was looking for on the web.. i dont know what keyword should i type or if i would, i got bunch of hard to understand one than to get an ABC explanatory kind of article for this kind of problem, and thank you norm. yes i see that.. even the 'last' points to itself. Please hang on me for a while, this is what i understand base on the articles kevin gave me, the "Cup with remote controls",..

    when the statement
    tempStart = last;
    tempNext = tempStart;
    tempStart.setNext(tempNext);

    i passed not a copy to a reference but instead i passed the thing that the 'last' controls into the variable tempStart?
    so whenever i do something USING the tempStart.. it will affect what the 'last' is referring to?

    is my understanding correct?

  13. #11
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Pass-by-Value scheme, puzzled with passing/assigning a reference to another objec

    tempStart = last;
    tempNext = tempStart;
    That sets the three variables to point to the same object. There is one object addressed by three reference pointers.
    If you don't understand my answer, don't ignore it, ask a question.

  14. The Following User Says Thank You to Norm For This Useful Post:

    chronoz13 (June 2nd, 2012)

Similar Threads

  1. PrintWriter: passing File reference vs String
    By kahwa in forum File I/O & Other I/O Streams
    Replies: 1
    Last Post: April 12th, 2012, 12:56 AM
  2. Object Reference
    By Mr.777 in forum Object Oriented Programming
    Replies: 2
    Last Post: June 13th, 2011, 03:03 AM
  3. 'pass by value' and 'pass by reference'
    By pokuri in forum Object Oriented Programming
    Replies: 5
    Last Post: January 26th, 2011, 11:30 AM
  4. Passing reference via object
    By Stefan_Lam in forum Java Theory & Questions
    Replies: 1
    Last Post: January 7th, 2011, 11:57 AM
  5. Object as Reference not working
    By jassi in forum What's Wrong With My Code?
    Replies: 4
    Last Post: March 9th, 2010, 09:47 AM