File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Arrays Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Arrays" Watch "Arrays" New topic


Ritu Kapoor
Ranch Hand

Joined: Oct 03, 2004
Posts: 102
Can anybody explain me this. Why is it returning:


public class Casting06 {

static void m1(int[] i4, int[] i5) {
int[] i3 = i4; i4 = i5; i5 = i3;
public static void main (String[] args) {
int[] i1 = {1}, i2 = {3}; m1(i1, i2);
System.out.print(i1[0] + "," + i2[0]);
Output:1,3 While the expected answer is 3,1
Raghu Shree
Ranch Hand

Joined: Mar 18, 2005
Posts: 143
When reference are passed as arguments we can't change the object reference. This changes are reflects only in called method.
If the method return the changes are revoked. So Array i1 and i2 has original reference in main method. So Output is displayed as 1,3. If we have change the object values instead of reference, this changes are also reflected in calling method.

Raghu J<br />SCJP 1.4<br /> <br />The Wind and waters are always<br />on the side of the ablest navigators.<br /><a href="" target="_blank" rel="nofollow">SCJP Group</a><br /><a href="" target="_blank" rel="nofollow">SCWCD Group</a>
Srinivasa Raghavan
Ranch Hand

Joined: Sep 28, 2004
Posts: 1228
See you have to keep in mind that a copy of reference is passed to the method m1.
Now try to execute this you 'll surely get to know thw concept more clearly.

Thanks & regards, Srini
MCP, SCJP-1.4, NCFM (Financial Markets), Oracle 9i - SQL ( 1Z0-007 ), ITIL Certified
Jimmy Thomas

Joined: Aug 17, 2005
Posts: 19
Hi Ritu,

In Java arrays are Objects, so when you call the method m1(int[] i4, int[] i5), the copy of the reference to these array objects are passed. Though you're manipulating the references inside the method it's valid only within the scope of the method m1(), once this method returns the array references are the same as before the call to method m1 is made.
Ritu Kapoor
Ranch Hand

Joined: Oct 03, 2004
Posts: 102
Thanx to all of you guys!
I agree. Here's the link:
subject: Arrays
It's not a secret anymore!