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
, androot3
are allnull
. -
Node root[]={root1,root2,root3}
is executed and it creates aNode[]
object (#1) with length of 3, and copies thenull
values ofroot1
,root2
, androot3
. 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 aNode
object (#2) and assigns it toroot[0]
. Note thatroot1
remainsnull
. -
root1=new Node(null,3)
is executed and creates aNode
object (#3) and assigns it toroot1
. Note thatroot[0]
still references #2. -
You print the value of
root[0].data
, and sinceroot[0]
references #2, it will print2
. -
You print the value of
root1.data
, and sinceroot1
references #3, it will print3
.
Everything works the way it should.
0
solved Object Array Initialization [duplicate]