Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

what is the Output?

 
sonir shah
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.

Sonir
 
Stefan Zoerner
Author
Ranch Hand
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,
Stefan
 
Jose Botella
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic