File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Problem with passing variables to a function. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of JavaScript Promises Essentials this week in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Problem with passing variables to a function." Watch "Problem with passing variables to a function." New topic
Author

Problem with passing variables to a function.

Subhadip Niyogi
Greenhorn

Joined: Aug 04, 2000
Posts: 1
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

Joined: Aug 04, 2000
Posts: 5
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

Joined: Jul 13, 2000
Posts: 29
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


hyby2000@yahoo.com
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Problem with passing variables to a function.