• 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

what is the Output?

 
Ranch Hand
Posts: 435
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Question ID :957709540380
What will be the output of compiling and running the following program?
class CloneTest
{
public static void main(String[] args)
{
int ia[ ][ ] = { { 1 , 2}, null };
int ja[ ][ ] = (int[ ] [ ])ia.clone();
System.out.print((ia == ja) + " ");
System.out.println(ia[0] == ja[0] && ia[1] == ja[1]);
}

Answer is :It will print 'false true' when run.Can anyone explain me how do we get such answer.

Sonir
 
Author
Posts: 121
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello Sonir!
You need to know three things to get the answer;
1. (ia == ja) evaluates to false
2. (ia[0] == ja[0]) evaluates to true
3. (ia[1] == ja[1]) evaluates to true
1. is abvious, because == tests for the same object, and the clone-method creates a new (different) instance
For 2. and 3. I would recommend you to add something like the following code in your program and start to figure out by experiments how clone operates on arrays ...

Greetings from Hamburg,
Stefan
 
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello Sonir
Cloning an object produces a new object whose fields are pointing to same objects pointed to by the fields of the original object. That is called a shallow copy, instead of a deep one, because the objects referred to by the original are not copied, only the references to them are copied and placed in the fields of the new object.
To that respect, the elements of an array are cloned as if they were fields of the array object. Thus ja second element will also be null. And the first element of ja will be pointing to the same int[] object pointed to by the first element in ia.
FYI an element of a multidimensional array points to another array object.
 
reply
    Bookmark Topic Watch Topic
  • New Topic