Meaningless Drivel is fun!
The moose likes Beginning Java and the fly likes Class Variable access 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 "Class Variable access" Watch "Class Variable access" New topic

Class Variable access

sanjay pathak

Joined: Mar 19, 2001
Posts: 2
class A
{ public static final int i = 10;
public ststic void main(String arg[])
int i = 23; // it compiles but if int i is replaced by i then
//error why
System.out.println("Value of i ="+i);
This confuses me since i is class variable then is it possible to define the variable with the same name as local in method
Bosun Bello
Ranch Hand

Joined: Nov 06, 2000
Posts: 1510
It's because "i" is declared to be final. A final variable can not be changed once it has been assigned a value. Take the final modifier off, and it will compile.

So much trouble in the world -- Bob Marley
sanjay pathak

Joined: Mar 19, 2001
Posts: 2
It is compiling with int i. Should it not give error saying that duplication of declaration.
Randall Twede
Ranch Hand

Joined: Oct 21, 2000
Posts: 4351

It is because the class variable is being shadowed by the local variable. From the JLS:
6.3.1 Shadowing Declarations

Since the scope of a class variable includes the entire body of the class (�8.2) the class variable x would normally be available throughout the entire body of the method main. In this example, however, the class variable x is shadowed within the body of the method main by the declaration of the local variable x.

Dont blindly believe everything I say.
[This message has been edited by Randall Twede (edited March 19, 2001).]

Visit my download page
subject: Class Variable access
It's not a secret anymore!