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 Language fundamental Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Language fundamental" Watch "Language fundamental" New topic

Language fundamental

Shilpa Bhargava
Ranch Hand

Joined: Sep 15, 2002
Posts: 39
Please take a look at the code below
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;

1.How can you define another integer array with the same name in the method.
Is it becoz the method is static so the non static code of the class is inaccessible to static part ??
2.why is the o/p 4 ?? Is it becoz a copy of the array reference is passed and not the value of i[0] ??
raju vegiraju

Joined: Sep 24, 2002
Posts: 5
I didn't understand ur first question but the o/p is 4 becos u are printing the i[0].which is 4 returned by ur method which has
i[0]*=2(i.e 4)
And also i[]={0} means ur storing 0 in the array i
Shilpa Bhargava
Ranch Hand

Joined: Sep 15, 2002
Posts: 39
Sorry about the ambiguity !! in simple words...can u define the same variable at the instance level as well as locally in a method ??
in this case
int[] i has been declared both inside and outside a method !!
Dirk Schreckmann

Joined: Dec 10, 2001
Posts: 7023
That is allowed and it does not relate to a static vs. instance situation.
You'll eventually see a constructor or method similar to this:In this example, instances of the class Foo are defined to have a private int member called number. This member is assigned a value from the constructor that has an automatic variable of type int also called number. To explicitly state when the instance member is to be used rather than the automatic variable, number is prefixed with this. .
Note that when using a member data item inside of any method (or constructor or initializer block), even though the programmer won't usually prefix its reference with this. when no local variable has the same name, the this. prefix is considered to be implied and I think the compiler does actually fully qualify each instance reference with the prefix this. .
So, um... is any of this making sense?
To answer your second question, take a look at Corey McGlone's flash animation on this very subject.

[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
Shilpa Bhargava
Ranch Hand

Joined: Sep 15, 2002
Posts: 39
Thanks Dirk,
It did clarify my doubt !!
[ September 24, 2002: Message edited by: Shilpa Bhargava ]
I agree. Here's the link:
subject: Language fundamental
It's not a secret anymore!