Ramgopal Ramgopal - 17 days ago 4x
Java Question

Object Array Initialization

I am reposting my question.

There are 3 reference variables root1,root2,root3,they are included in a reference array (root[]={root1,root2,root3}).

I initialized the object for root[0],I hope root[0] refers to root1 ,So i expect root1.data and root[0].data to access the same value.But i am not able to access using root1.data whereas i am able to access it using root[0].data.

public class testing
static Node root1,root2,root3;
public static void main(String[] args)
Node root[]={root1,root2,root3};
root[0]=new Node(2,null);
System.out.println("root[0]="+root[0].data);//It is working properly
System.out.println("root1="+root1.data);//It is not working properly
public static class Node
int data;
Node next;
Node(int data,Node next)


Variables and array elements are all references to objects. They are not the actual objects.

To illustrate, I'll "name" actual objects using a number scheme, e.g. #1 is the first object.

Your code runs as follows:

  • Class is initialized by the JVM, and root1, root2, and root3 are all null.

  • Node root[]={root1,root2,root3} is executed and it creates a Node[] object (#1) with length of 3, and copies the null values of root1, root2, and root3. The code is equivalent to:

    Node[] root = new Node[3];
    root[0] = root1;
    root[1] = root2;
    root[2] = root3;
  • root[0]=new Node(null,2) is executed and creates a Node object (#2) and assigns it to root[0]. Note that root1 remains null.

  • root1=new Node(null,3) is executed and creates a Node object (#3) and assigns it to root1. Note that root[0] still references #2.

  • You print the value of root[0].data, and since root[0] references #2, it will print 2.

  • You print the value of root1.data, and since root1 references #3, it will print 3.

Everything works the way it should.