aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes clone from Dans Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "clone from Dans" Watch "clone from Dans" New topic
Author

clone from Dans

sun par
Ranch Hand

Joined: Oct 03, 2002
Posts: 257

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


Sunita<br />SCJP 1.4
Corey McGlone
Ranch Hand

Joined: Dec 20, 2001
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.


SCJP Tipline, etc.
sun par
Ranch Hand

Joined: Oct 03, 2002
Posts: 257
Thanks Corey for the clear and quick reply.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: clone from Dans