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

Problem with passing variables to a function.

 
Subhadip Niyogi
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi everybody.
The following code appeared in a moc test.
public class example {
int i[] = {0};
public static void main(String args[]) {
int i[] = {1};
change_i(i);
System.out.println(i[0]);
}
public static void change_i(int i[]) {
int j[] = {2};
i = j;
}
}
the answer for this is 1.
But if you change the last line of the method change_i to
i[0]=j[0], it prints 2. What's the logic??
 
Rajasekar Loganathan
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Subhadip Niyogi:
Hi everybody.
The following code appeared in a moc test.
public class example {
int i[] = {0};
public static void main(String args[]) {
int i[] = {1};
change_i(i);
System.out.println(i[0]);
}
public static void change_i(int i[]) {
int j[] = {2};
i = j;
}
}
the answer for this is 1.
But if you change the last line of the method change_i to
i[0]=j[0], it prints 2. What's the logic??

Hi ,
when you pass the array i to the change_i method you are
giving the reference to the method. Inside the method
you are assigning the reference to the other local
array i (ie i=y . When you come out of the method nothing
has changed in the array i so the old value will be printed.
When you say i[0] = y[0] you are changing the value using
the reference you caught in the change_i methods local i,so
it reflects in the called method.
Bye,
Sekar.
 
Helen Yu
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,there:
please visit http://www.javaranch.com/ubb/Forum24/HTML/002409.html
hope this help, yesterday I got it clearly, this is pretty cool.
regs
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic