• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Ron McLeod
  • paul wheaton
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
  • Himai Minh
Bartenders:

Problem with passing variables to a function.

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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??
 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
reply
    Bookmark Topic Watch Topic
  • New Topic