File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes passing parms to method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "passing parms to method" Watch "passing parms to method" New topic
Author

passing parms to method

Narayanan Kallamvalli
Greenhorn

Joined: May 25, 2004
Posts: 3
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;
}
}

when I run this program I get 1 .but my question is

what is the result of i=j; why it is not changing the value of i[] in the main method.


thanks
Nathaniel Stoddard
Ranch Hand

Joined: May 29, 2003
Posts: 1258
This is a simple question that tests you knowledge of the fact that Java passes all variables by value (i.e. it copies the value and then passes it to the function).

In this case, what you are going to get is a copy of the reference variable that points to the same array. HOWEVER, when you say "i = j", all you are doing is changing your "copy" of the reference variable. It will have no effect on the value that was used when the function was called.

The only way to change the value of something that is passed in through a variable is through methods and that sort of thing, e.g. i.setValue(1) etc. I hope this clears up some stuff for you.


Nathaniel Stodard<br />SCJP, SCJD, SCWCD, SCBCD, SCDJWS, ICAD, ICSD, ICED
Dirk Schreckmann
Sheriff

Joined: Dec 10, 2001
Posts: 7023
Narayanan, you might like to read the "Pass-by-Value Please" story of the JavaRanch Campfire Stories.


[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: passing parms to method