• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

clone from Dans

 
Ranch Hand
Posts: 257
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

can someone please explain what the clone does and why the o/p is 112?
Thanks
 
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Corey for the clear and quick reply.
 
reply
    Bookmark Topic Watch Topic
  • New Topic