Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

passing array to method

Status
Not open for further replies.

deva1

Programmer
Oct 28, 2002
27
US
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

 
The scope of array j is within the method change_i, so array i reference to array j is useless. We cannot reference to a local literal or object outside their method.

public class example {
static 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[0] = j[0];
}
}
 
// avoid to use same variable name for different scope
public class example {
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[0] = j[0];
}
}
 
deva1 :

Why have you posted the same question in two different threads in the same forum (see deva1's previous post) ?
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top