File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes what is the Output? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "what is the Output?" Watch "what is the Output?" New topic
Author

what is the Output?

sonir shah
Ranch Hand

Joined: Nov 01, 2001
Posts: 435
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

Joined: Nov 29, 2001
Posts: 121
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


Stefan Zoerner
Author of German LDAP-Book
Committer at Apache Directory Project
Jose Botella
Ranch Hand

Joined: Jul 03, 2001
Posts: 2120
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.


SCJP2. Please Indent your code using UBB Code
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: what is the Output?
 
Similar Threads
problem with clone.......
clone method
Array
JQplus
Clone