Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

passing parms to method

 
Narayanan Kallamvalli
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1258
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Narayanan, you might like to read the "Pass-by-Value Please" story of the JavaRanch Campfire Stories.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic