File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes java variable scope Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "java variable scope" Watch "java variable scope" New topic

java variable scope

Narayanan Kallamvalli

Joined: May 25, 2004
Posts: 3
public class example {
int i[] = {0};
public static void main(String args[]) {
int i[] = {1};
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?

Nathaniel Stoddard
Ranch Hand

Joined: May 29, 2003
Posts: 1258
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

Joined: May 25, 2004
Posts: 3
Thank you very much
Preetham Chandrasekhar
Ranch Hand

Joined: Nov 05, 2003
Posts: 98
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};
//this wont affect the value of i in the calling method either

hope it helped

SCJP 1.4

"In theory, there is no difference between theory and practice. But, in practice, there is."<br /> - Jan L.A. van de Snepscheut
I agree. Here's the link:
subject: java variable scope
It's not a secret anymore!