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 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

Shadowing Variables

Laloo Bond

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);
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.
I agree. Here's the link:
subject: Shadowing Variables
It's not a secret anymore!