Question

Possible Duplicate:
Java, pass-by-value, reference variables

I am a bit confused on how exactly JAVA pass by value works with object. For e.g. if I pass a object as a parameter to the method. I understand that its address is passed as value. Ok, is a duplicate of the object is kept at the original place form where the object is passed, because if I create a new reference to the object in the called API and change something in it, it doesn't get reflected in my caller API.

Below is a typical piece of code where I try to delete a tree but it's still there.

public class DeleteTree {

public static void main(String[] args) {

    Node root = new Node(5);
    for(int i = 0 ; i < 10 ; i++){
        if(i == 5) continue;
        root.insertNode(i);
    }

    deleteTreeNonRecursive(root);
    System.out.println(root.key);

}

public static void deleteTreeNonRecursive(Node root){

    Queue<Node> q = new LinkedList<Node>();
    q.add(root);
    while(!q.isEmpty()){
        Node temp = q.poll();
        if(temp.leftChild != null)q.add(temp.leftChild);
        if(temp.rightChild != null)q.add(temp.rightChild);
        temp = null;
    }

}

Expected O/P: nullpointer exception.

Actual O/P: 5.

Was it helpful?

Solution

In Java you always pass by value the reference to the object (which is itself allocated onto the heap). No duplication occurs because you are just passing pointers around.

In your example you are just setting temp = null but this indeed does nothing just because temp is a pointer to a Node but it's a variable local to the function, when you set it to null the original object is not touched at all just because you are just modifying the value of the reference without modifying the referenced object.

To delete the tree this is the only thing you need:

Node root = new Node(5);
    for(int i = 0 ; i < 10 ; i++){
        if(i == 5) continue;
        root.insertNode(i);
    }

root = null;

OTHER TIPS

Java always uses pass by value. It's the value of the reference that is passed when it comes to object references. When you pass an object reference, it's a copy of the reference value which is passed. Using that, you can always access the object and change its properties (wherever applicable), but assigning that reference to another object or null has no consequences to the original reference in the calling method obviously.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top