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

Arrays

 
Ritu Kapoor
Ranch Hand
Posts: 102
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can anybody explain me this. Why is it returning:

1,3

Code:
--------------------------------------------------------------------------
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
Posts: 143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Srinivasa Raghavan
Ranch Hand
Posts: 1228
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Jimmy Thomas
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 102
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanx to all of you guys!
 
Don't get me started about those stupid light bulbs.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic