• 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 all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Bear Bibeault
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Knute Snortum
  • Junilu Lacar
  • paul wheaton
Saloon Keepers:
  • Ganesh Patekar
  • Frits Walraven
  • Tim Moores
  • Ron McLeod
  • Carey Brown
  • Stephan van Hulst
  • salvin francis
  • Tim Holloway

what is the Output?  RSS feed

Ranch Hand
Posts: 435
  • Mark post as helpful
  • send pies
  • 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.

Posts: 121
  • Mark post as helpful
  • send pies
  • 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,
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
  • 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.
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!