File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Shadowing Variables Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Reply locked New topic
Author

Shadowing Variables

Laloo Bond
Greenhorn

Joined: Jun 06, 2008
Posts: 5
package ShadowVariable;

class Foo {

static int size=7;

static void changeIt(int size){
size = size + 200;
System.out.println("size inside changeIt " + size);
}

public static void main(String[] args) {
System.out.println("Before modify size variable " + size);
changeIt(size);
System.out.println("size After changeIt " + size);
}
}

The output of this program is :
-------------------------------
Before modify size variable 7
size inside changeIt 207
size After changeIt 7


Am little bit confused about the behaviour of this program's output.
As per my knowledge,here SIZE is a static variable and it should be unique.
I believe that is main purpose of static variables and it is accessed globally without creating instance of it.

But here in the changeIt(int size) method, as soon as we create the local(method) variable as the same name of static variable, the global variable is shadowed(hidden) by the local variable.

I thought the output is like :
Before modify size variable7
size inside changeIt207
size After changeIt 207

because size is global variable and unique as it is static.

Could you please explain how it is working and what is the priority and scope of both method(local) variable and static(global) variable.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Shadowing Variables
 
Similar Threads
Mistake(I think) on K&B's 1.4 book
Is the program given wrong in K&B Book?
Referenec passing vs. Valuse passing
Shadowing Variables
shadowing an variable