1

In Java programs, is it right to set an object equal to another one? To be more specific, I'm studying binary trees and I noticed in the following code:

public Node find(int key)
{
    Node current = root;
    while(current.iData != key) 
    {
        if(key < current.iData)
        {
            current = current.leftChild;
        } else {
            //...
        }
    }
}

that both Node current = root; and current - current.leftChild; are setting an object equal to another one. Is this right?

ChiefTwoPencils
  • 13,548
  • 8
  • 49
  • 75
nikos_k
  • 49
  • 1
  • 4

2 Answers2

2

setting an object equal to another one. Is this right?

No, that's not right.


What's actually happening is, you're changing the reference of one variable to another object.

So:

Node current = root; // "current" will point at the same object as `root`.

and

current = current.leftChild; // "current" will point at the same object as `leftChild`.

note -

When assigning primitive types with = is a completely different behaviour when assigning reference types with =.

Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
  • 1
    Good answer, I just want to add that for further reading the OP can find more details in the [Java Tutorial on Creating Objects](https://docs.oracle.com/javase/tutorial/java/javaOO/objectcreation.html). – D.B. Oct 28 '17 at 16:31
1

First of all, you need to need a basic concept in Java: Java does manipulate objects by reference, and all object variables are references.

So when you have Object o1 and Object o2, in fact o1 and o2 are just references to memory spaces that hold the object not the object itself.

When you have o1 == o2 , you are comparing the two references not the objects themselves but if you want to compare them you need to override the equals() method.

Now, let's talk about your case:

Node current = root; this means that current and root are referring to the same object (the same location in memory). So there is only one object and two references.

Houssam Badri
  • 2,441
  • 3
  • 29
  • 60