Search code examples
javatreebinary-treepass-by-value

Java: How does passing uninstantiated object references work?


Here's an example of what I mean.

If I have a binary tree insert method that accepts a node, and I pass it parent.child (which is uninstantiated) what exactly is being passed?

Since Java is pass by value it must be passing a copy of the reference but without any object to point to what will happen? Does that mean I'm passing an empty reference that has no relevance to the parent node?

Unfortunately I don't have any code since this was actually a question that was passed onto me and I couldn't quite put it together. My solution was to pass a parent node which is already instantiated and then instantiate parent.child


Solution

  • Here's an example. Consider the type

    class Node {
        Node child;
    }
    
    Node parent = new Node();
    // here, parent.child == null
    

    So, assuming null is a special value, say 0x0000, somewhere in memory (YMMV), there's a

    0x1000: Start of Node Object
    0x1004: 0x0000 (child field offset)
    ...
    0x6000: 0x1000 (parent variable)
    

    In other words, there's a Node object, with a child field storing null as its value. Additionally, there's a variable parent storing the value (an address of sorts) of the Node object.

    When you do

    public void insert(Node node) {/* implementation */}
    ...
    tree.insert(parent.child);
    

    You're dereferencing parent, thereby getting its address, 0x1000, figuring out at which offset its child field is, 0x1004, and getting its value, 0x0000. You then copy that value on the stack. The method invocation will pop that value from the stack and bind it to this new node variable. So now you have

    0x1000: Start of Node Object
    0x1004: 0x0000 (child field offset) // null
    ...
    0x6000: 0x1000 (parent variable)
    ...
    0x8000: 0x0000 (node variable) // null
    

    To answer your question

    Does that mean I'm passing an empty reference that has no relevance to the parent node?

    You're passing a null reference. There will be no way to retrieve whatever parent was referencing from the bound parameter.