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!

java variable scope

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[]) {
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









 
A primitive array (ie int[]) is actually a mutable object - so if you pass it to a method and alter the contents in that method - then it is modified.

Its all about how Java handles passing objects by *reference or value?*, and whether an object is mutabale.

Read up on the subject :

 
You have a class-variable int i [], which is hidden in main, where you have a local i.
Your method gets a parameter i, which hides again the class-attribute.

- Write the class name in uppercase.
- Call
Code:
Example example = new Example ();
as first statement in main.
Now you have an example, and therefore an i.
- Remove the 'static'-keyword.
- call change_i without parameter.
- initialize i without telling again 'int array':
Code:
i = new int [1];
i[0]=1;


seeking a job as java-programmer in Berlin:
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top