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.