Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

java variable scope

 
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[]) {
i[0] = 2;
i[0] *= 2;
}
}


Can anyone tell how the scope of the array int i[] works? I thought if we declare something inside a method it is local to that method.Here int i [] declared inside example(class level) and then inside main method and change_i mehtod.If I run this program it prints 4 . why? Since it is declared inside main method i [] = {1}; I thought it will print 1.Hello Gurus I am bit confused,please help me to understand this?

Thanks
 
Nathaniel Stoddard
Ranch Hand
Posts: 1258
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you read my response to your other question, you now know the rules about altering values that get passed into funtions. As a refresher, setting "i = j" won't have any influence on the actual variable that was used to invoke the function. Now, in this case you're not trying to set it to a different value altogether. You are only altering the contents of it, which is completely allowed since both "copies" of the reference variable refer to the same array.

That is why the change_i function's work will be seen once the method returns and the value is printed out.
 
Narayanan Kallamvalli
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you very much
 
Preetham Chandrasekhar
Ranch Hand
Posts: 98
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the method if u say ....

changeto (int[] i){
i[0]=2 ; this is going to affect the actual value...
//now if u say
i = new int[]{2};
//this wont change ur value of i in the calling method
...
....
//or even if u say
int j[] = new int[]{1,2,3};
i=j;
//this wont affect the value of i in the calling method either


hope it helped

Preetham
SCJP 1.4
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic