[Solved] Object Array Initialization [duplicate]


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.

0

solved Object Array Initialization [duplicate]