Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!

# clone from Dans

sun par
Ranch Hand
Posts: 257

can someone please explain what the clone does and why the o/p is 112?
Thanks

Corey McGlone
Ranch Hand
Posts: 3271
The clone method really just makes a "copy" of the object you cloned. Note that, by default, the copy that you make is a shallow copy, not a deep copy. You can find more information on that in the API Spec.
For this question, however, let's just look through this code.

This line declares a 2-dimensional array and initialized its contents.

This line "makes a copy" of that object. Because we're dealing with a shallow copy, nothing new is really created. Instead, obj is effectively referencing at the same data that a is referencing.
Now, we go on to the loop.

Okay, nothing strange here. We initialize our counter to 0 and we're going to loop through the length of the array (in this case the array is 3 elements long, each element is a reference to another array).

In this line, we're accessing object obj[i] (i is 0 the first time through, so we're accessing obj[0]). Well, from our diagram, we can see that obj[0] is an array of integers that looks like this:

Going on, we find the next line of code:

Going back to the last diagram, we see that ia[0] is equal to 1, so we print out a 1.
Now, we start the loop over with i = 1. Based on that, we get the second element of obj, which is this array:

And, when we get to the print statement, we print the second element of the array (remember, i is now 1), which is 1.
Likewise, for the third iteration, we get the third array and print the third element of that array, which is 2.
Therefore, the output is 112.
I hope that helps,
Corey
P.S.
Never underestimate the power of a sketch.

sun par
Ranch Hand
Posts: 257
Thanks Corey for the clear and quick reply.